Kugel
Kugel

Reputation: 19824

How do I bind to different property on ComboBox SelectedItem?

I have a combobox in WPF like this:

<ComboBox Text="Select Language..." IsEditable="True" IsReadOnly="True"
          ItemsSource="{Binding XPath=item/@name, Source={StaticResource Items}}"
          SelectedItem="{Binding Path=Test, Mode=OneWayToSource}"/>

Where Items is:

<XmlDataProvider x:Key="Items" Source="/itemlist.xml" XPath="/itemlist"/>

Test is a property of type object on ViewModel that is set as datacontext of a window.

Everything works fine, and my Test property receives XmlNode object, which makes sense.

However, I would like to receive different attribute from that xml for example XPath=item/@value

How do I do that?

Upvotes: 0

Views: 1271

Answers (1)

Quartermeister
Quartermeister

Reputation: 59139

Use DisplayMemberPath and SelectedValuePath:

<ComboBox Text="Select Language..." IsEditable="True" IsReadOnly="True"
  ItemsSource="{Binding XPath=item, Source={StaticResource Items}}"
  DisplayMemberPath="@name"
  SelectedValuePath="@id"
  SelectedValue="{Binding Path=Test, Mode=OneWayToSource}"/>

The selected item will be the item element, it will display the name attribute, and it will bind the id attribute to Test.

Upvotes: 1

Related Questions