我正在尝试以编程方式更改 ComboBoxItem 模板
//Main Style
Style style = new Style() { TargetType = typeof(ComboBoxItem) };
//Set Template
ControlTemplate temp = new ControlTemplate(typeof(ComboBoxItem));
style.Setters.Add(new Setter() { Property = Control.TemplateProperty, Value = temp });
//Item Border
FrameworkElementFactory itemB = new FrameworkElementFactory(typeof(Border));
itemB.SetValue(Border.BorderBrushProperty, Brushes.Red);
itemB.SetValue(Border.WidthProperty, (double)500);
itemB.SetValue(Border.HeightProperty, (double)30);
itemB.SetValue(Border.BorderThicknessProperty, new Thickness(2));
itemB.SetValue(Border.BackgroundProperty, Brushes.GreenYellow);
temp1.VisualTree = itemB;
//Item Label
FrameworkElementFactory itemT = new FrameworkElementFactory(typeof(Label));
itemT.AppendChild(itemB);
itemT.SetValue(Label.ForegroundProperty, Brushes.Red);
/* This Part Is Not Working*/
itemT.SetBinding(Label.ContentProperty, new Binding { RelativeSource = RelativeSource.Self });
//Set Template
Application.Current.Resources[typeof(ComboBoxItem)] = style;
我也尝试过这个
itemT.SetBinding(Label.ContentProperty, new Binding { Source = ComboBoxItem.ContentProperty });
问题是项目名称未显示在下拉列表中。
这就是我添加组合框的方式
//ComboBox
ComboBox combobox = new ComboBox() {Height = 30, Width = 500};
combobox.Items.Add("OK 1");
combobox.Items.Add("OK 2");
combobox.Items.Add("OK 3");
combobox.Items.Add("OK 4");
这是我的下拉列表的样子
除此之外,还不清楚为什么您不简单地在 XAML 中执行此操作
itemT.SetBinding(Label.ContentProperty,
new Binding { RelativeSource = RelativeSource.Self });
和
itemT.SetBinding(Label.ContentProperty,
new Binding { Source = ComboBoxItem.ContentProperty });
错了。
在 ControlTemplate 中,您将绑定到 模板化父元素:
itemT.SetBinding(Label.ContentProperty,
new Binding { RelativeSource = RelativeSource.TemplatedParent });