ComboBox SelectedItem and ItemsSource: Order Matters
A co-worker of mine had a strange issue with a bound combo box that looked like this:
<ComboBox x:Name="cboParentUser" ItemsSource="{Binding Path=Order.Store.Users, ElementName=me, Mode=Default}" SelectedItem="{Binding Path=Order.ParentUser, ElementName=me, Mode=Default}" IsEditable="False" DisplayMemberPath="UserName" />
As we could observe at runtime, selecting an item in the combo box properly updated the underlying ParentUser property. Furthermore, we could easily exchange the data context (Order dependency property) in order to edit different items.
However: As soon a the editor control that contained the combo box was unloaded, the ParentUser property of the currently edited Order was set to null, so all previously made adjustments were lost.
The reason behind this behavior seems to be the fact that both ItemsSource and SelectedItem are bound to the same dependency property: Apparently, when Order is set to null during unloading, WPF realizes that the ItemsSource is no longer valid, and therefore clears the SelectedItem, to which the combo box still appears to hold a reference at this moment - which brings it down to a question of proper coercion. Or maybe not - the reason behind this is not entirely clear to me.
However: Changing the declaration order of SelectedItem and ItemsSource fixes the problem:
<ComboBox x:Name="cboParentUser" SelectedItem="{Binding Path=Order.ParentUser, ElementName=me, Mode=Default}" ItemsSource="{Binding Path=Order.Store.Users, ElementName=me, Mode=Default}" IsEditable="False" DisplayMemberPath="UserName" />
And yes: This does feel like a dirty hack.
Same thing here.
Dose anyone have an explanation for this strange behavior?
Wow… I wasted alot of time cursing WPF and trying to find a solution to the problem you describe above. Thankfully your fix addresses the issue, but I agree this does feel like a dirty hack.
Whilst .NET and particularly wpf xaml is code-order-sensitive, incorrectly ordered code (leading to missing references) is usually picked up as a compile-time, or run-time exception. This however is not and cannot be desired behviour!
OMG! Thanks for posting this! I was having the same problem and couldn’t figure out why. It still doesnt’ make sense why the order of the properties in the XAML should make sense, but at least I have a solution to the problem without having to code gobs of properties to store and re-assign old values!
Again, Thanks a ton!
And Yes…It most definitely feels like a dirty hack, but it works!
Thanks!
it’s not only SelectedItem. With Text or SelectedValue are the same problems…