Archive

Posts Tagged ‘xaml’

ComboBox SelectedItem and ItemsSource: Order Matters

January 14th, 2009

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.

Author: Categories: WPF, WPF Controls Tags: ,