ItemsSource and SelectedItem

Uncategorized

8 years ago

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}">
</ListView>

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}">
</ListView>

The devil is in the details.