I have a view with a ComboBox like this
<ComboBox Name="cmbPurpose" DisplayMemberPath="@value" SelectedValuePath="@key"
ItemsSource="{Binding Source={StaticResource Purposes}, XPath=purpose}"
SelectedItem="{Binding Path=Purpose, Mode=TwoWay}" />
I also set the DataContext of the view to my viewmodel. On my viewmodel i have a property ‘Purpose’ of type ‘XmlElement’ bound to SelectedItem. I would have liked it to be a string that corresponded to the @key in my xml, but i can live with this since it makes sence in a view-viewmodel context.
When i change the ComboBox, i can observe that the value in my viewmodel changes accordingly – which is as expected (and good).
When i populate my view with the viewmodel, i need some defaults set (also it will be used to edit a model later so i will need to be able to set all properties on my viewmodel). How do i set the correct value on my viewmodel’s ‘Purpose’ property? The data from my model is really equal to the @key of my xml, but the viewmodel or whatever populates my viewmodel have no way of knowing what resource to look in since it needs to set an XmlElement.
So what is best practise here? Should i move the static resource to my viewmodel or is there another way of solving this? How is this normally done? Is static resources just bad in this situation? It would be perfect if i could just make the viewmodel.Purpose into a string and have it bind to the @key instead of the whole object – that should solve the problem as i could both set and read viewmodel.Purpose without having to think of the source being xml, right?
EDIT: If there was a way to do SelectedKey="{Binding Path=Purpose, Mode=TwoWay}" and changing the viewmodel.Purpose to a string, then the problem would be sovled.
You can set the selected value to the
key…. simply useSelectedValueinstead ofSelectedItem, and bind it to a string value which corresponds with the an@keyin yourItemsSourceIt should be noted that ComboBoxes compare items by reference, so if you do use
SelectedItemthen the item that is bound needs to contain the exact same reference in memory as the item in theItemsSource.For example,