ItemsSource and SelectedItem

Quite a common mistake that XAML developers do here and there (especially myself, I just can’t stop causing this bug…) is to switch the order the ItemsSource and SelectedItem properties in XAML while building a MVVM pattern based app.

Let’s see it in context the WinRT ListView control. To bind some items to it we use the ItemsSource dependency property. To select one of them we bind to SelectedItem.

Looks great right? Not yet.

XAML parser processes the file in the left right order. This way the first dependency property it faces is the SelectedItem. Here it tries to select the item in the collection, but unfortunately, it cannot be found. In that moment the SelectedItem of the ListView is actually set back to null. Now the ItemsSource is reached normally, but it is too late to get the SelectedItem back “from the dead”.

The correct order only when SelectedItem is placed behind the ItemsSource. Then we get the desired results and will no longer get unexpected, hard to decode behavior.

 The devil is in the details.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

*