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";
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);
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