Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an ItemTemplate for a ComboBox programmatically?

Tags:

c#

wpf

xaml

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?

like image 719
TorbenJ Avatar asked Dec 05 '25 14:12

TorbenJ


1 Answers

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.

like image 166
abhishek Avatar answered Dec 08 '25 04:12

abhishek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!