I would like to create an ItemTemplate for a ComboBox programmatically (like the topic says).
At the moment I have an ItemTemplate in XAML:
<Style x:Key="ComboBox_EntityCreation_GroupSelect_Style" TargetType="{x:Type ComboBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1} Mitglied(er)">
<Binding Path="Name"/>
<Binding Path="MemberCount"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
As a result of my hatred for XAML I would like to get the result without XAML.
Is it possible to do this?
I have just converted this on the fly. Please check whether it works.
Style style = new Style(typeof(ComboBox));
var d = new DataTemplate();
MultiBinding mb = new MultiBinding();
mb.StringFormat = "{0} {1} Mitglied(er)";
mb.Bindings.Add(new Binding("Name"));
mb.Bindings.Add(new Binding("MemberCount"));
FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, mb);
d.VisualTree = textElement;
style.Setters.Add(new Setter(ComboBox.ItemTemplateProperty, d));
this.Resources.Add("ComboBox_EntityCreation_GroupSelect_Style", style);
You can assign a DataTemplate to its VisualTree using FrameworkElementFactory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With