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.

<ListView SelectedItem="{Binding SelectedPerson}" ItemsSource="{Binding People}">

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.

<ListView ItemsSource="{Binding People}" SelectedItem="{Binding SelectedPerson}">

 The devil is in the details.

Buy me a coffeeBuy me a coffee

1 thought on “ItemsSource and SelectedItem”

  1. I have checked your blog and i have found
    some duplicate content, that’s why you don’t rank high in google’s
    search results, but there is a tool that can help you
    to create 100% unique content, search for: Boorfe’s tips unlimited content

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> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


This site uses Akismet to reduce spam. Learn how your comment data is processed.