Monday, November 15, 2010

WPF ComboBox and XAML parser

For the past few days I have been trying to figure out why my ComboBox didn't work when I selected an item from a list of data-bound items. I've gone through the code over and over, tried different types of collections and different ways of accessing the selected item (SelectedValue or SelectedItem as int, string or object). Nothing worked.

Data-binding to a ComboBox in WPF/Silverlight isn't always as smooth as one would assume. People have problems here, here and there. The XAML was fairly easy to lay out, I thought. I had:

<ComboBox SelectedItem="{Binding Path=ReferenceType}"

="{Binding Path=ReferenceTypes}" />

It wasn't until I read "I always set the ItemSource before the SelectedItem and all works fine." that I thought I'd try switching my code to:

<ComboBox ItemsSource="{Binding Path=ReferenceTypes}" 

="{Binding Path=ReferenceType}" />

This way I define ItemsSource before SelectedItem. However, I never thought for a second that the XAML parser would care. I assumed the parser would figure out that it needs to know about the collection before it cared about what was selected. Obviously, if this were c# code I'd always specify the collection first, but this was XML, what does it care about the order of attributes?

I had broken the first rule of programming, never assume.

No comments:

Post a Comment