I am setting custom comboBox ControlTemplate but DataTemplate of ComboBoxItem is not getting bind with list.
//Main Style
Style style = new Style() { TargetType = typeof(ComboBox) };
//Set Template
ControlTemplate temp = new ControlTemplate(typeof(ComboBox));
style.Setters.Add(new Setter() { Property = Control.TemplateProperty, Value = temp });
FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
temp.VisualTree = border ;
border.SetValue(Border.BorderThicknessProperty, new Thickness(1));
border.SetValue(Border.BorderBrushProperty, Brushes.Red);
/* ControlTemplate Code */
//Data Template
DataTemplate itemTemp = new DataTemplate(typeof(ComboBoxItem));
//Item Text
FrameworkElementFactory itemText = new FrameworkElementFactory(typeof(TextBlock));
itemTemp.VisualTree = itemText;
itemText.SetValue(TextBlock.ForegroundProperty, Brushes.Red);
//Bind Not Working
Binding binding = new Binding();
binding.Source = ComboBox.ItemsSourceProperty;
itemText.SetBinding(TextBlock.TagProperty, binding);
//Set Template
style.Setters.Add(new Setter(ComboBox.ItemTemplateProperty, itemTemp));
Application.Current.Resources[typeof(ComboBox)] = style;
In this combobox DataTemplate is not getting applied but items name are showing.
ComboBox combobox1 = new ComboBox() {Height = 30, Width = 200};
combobox1.Items.Add(new ComboBoxItem() { Tag = "My Name 1", Content = "Item 1 1", Name = "Item1" });
combobox1.Items.Add(new ComboBoxItem() { Tag = "My Name 2", Content = "Item 2 2", Name = "Item2" });
combobox1.Items.Add(new ComboBoxItem() { Tag = "My Name 3", Content = "Item 3 3", Name = "Item3" });
combobox1.Items.Add(new ComboBoxItem() { Tag = "My Name 4", Content = "Item 4 4", Name = "Item4" });
//In this combobox DataTemplate is getting applied but items name are not showing.
ComboBox combobox2 = new ComboBox() {Height = 30, Width = 400};
combobox2.Items.Add("Item 1");
combobox2.Items.Add("Item 2");
combobox2.Items.Add("Item 3");
combobox2.Items.Add("Item 4");