Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ComboBox.DisplayMemberPath options?

I am binding a collection of objects to a ComboBox. What I want to achieve is a combobox that displays two properties of my object. However, I haven't figured out how to make a combobox display multiple DisplayMemberPaths. Is this possible?

This is how I'm currently setting up my Binding, and setting the DisplayMemberPath:

Binding comboBinding = new Binding();
comboBinding.Source = squad_members; //squad_members is the object collection

BindingOperations.SetBinding(Character_ComboBox, ComboBox.ItemsSourceProperty, comboBinding);
Character_ComboBox.DisplayMemberPath = "Name"; //
//Character_ComboBox.DisplayMemberPath = "Name" + "Age"; //failed attempt
Character_ComboBox.SelectedValuePath = "Name";
like image 464
user2453973 Avatar asked Dec 04 '22 05:12

user2453973


1 Answers

First of all you should do the binding in XAML instead of code behind.

You can provide ItemTemplate and use StringFormat in MultiBinding like this:

<ComboBox ItemsSource="{Binding YourCollection}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0} - {1}">
                        <Binding Path="Name"/>
                        <Binding Path="Age"/>
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

In case you want to do binding still in code behind.

You can omit setting DisplayMemberPath altogether by overriding ToString() method in your underlying source class. Since, internally ToString() gets called if DisplayMemberPath is not provided.

Say you collection is of type List<Person>, so you can override ToString() on Person class:

public override string ToString()
{
    return Name + Age;
}

With this in place, binding will look like this (DisplayMemberPath not needed)

Binding comboBinding = new Binding();
comboBinding.Source = squad_members; //squad_members is the object collection

BindingOperations.SetBinding(Character_ComboBox,
                   ComboBox.ItemsSourceProperty, comboBinding);
like image 135
Rohit Vats Avatar answered Dec 27 '22 17:12

Rohit Vats