Thursday, September 16, 2010

WPF ComboBox Retardation

A colleague found an "interesting" issue with ordering of XAML attributes on ComboBoxes in WPF the other day. His email says it well:

Dear nerds,

We can all tell tales about how tarded WPF is, but this one comes right at the top of my list. In markup languages the sequence of attributes in a tag don't have any significance, but in XAML which is happy child of the markup family this seems to have a significance that is never mentioned. This should not concern independent attributes but the ones that do depend on each other may not work properly if specified the wrong way around. An example which I battled with today is when specifiying the binding for source and selected value in a combo box. The correct order is:

Wrong:

<ComboBox Grid.Row="2" Grid.Column="2" Style="{StaticResource ComboBoxStyle}" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="MAPSSubCategoryValue" SelectedValuePath="MAPSSubCategoryId" ItemsSource="{Binding Path=SubCategories, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" SelectedItem="{Binding Path=SelectedMAPSSubCategory, Mode=OneWayToSource, ValidatesOnDataErrors=True}" />

Correct :

<ComboBox Grid.Row="2" Grid.Column="2" Style="{StaticResource ComboBoxStyle}" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="MAPSSubCategoryValue" SelectedValuePath="MAPSSubCategoryId" SelectedItem="{Binding Path=SelectedMAPSSubCategory, Mode=OneWayToSource, ValidatesOnDataErrors=True}" ItemsSource="{Binding Path=SubCategories, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" />

ItemsSource should be placed after SelectedItem. The reason behind it is quite unreasonable (which defies the purpose of a reason) but seems to be caused by the fact that these two properties are essentially bound to the same dependency property. In fact SelectedItem is bound to a subset of ItemsSource, so when WPF goes and re-sets these in the order specified :), if items source is first, it invalidates the selection for SelectedItem, but that does not happen the other way around.

This should not matter for other cases in which the dependency properties are independent, but you'd be surprised.

Cheers, Shuku

Labels: ,

0 Comments:

Post a Comment

<< Home