Bug in WPF combobox databinding

Sébastien Van Bruaene

Last week I exprienced an annoying bug in the WPF combobox databinding. One of the forms that I am developing consists of a master-detail view. The master is selected in a listview which is data bound to a list of contact person viewmodels. When selecting an item in the listview the databinding of the detail view changes to the viewmodel of the selected contact person. On the detail view there is a combobox of which the items are data bound to a list of countries and the selecteditem is data bound to the country of the contact person.

<ComboBox ItemsSource="{Binding Countries, Mode=OneWay}"
SelectedItem="{Binding SelectedCountry}"
DisplayMemberPath="Name" >

The bug I experienced was that when switching to another contact person in the master listview and then switching back to the original contact person the selected country in my viewmodel was always set to null so the contact person's country was lost. I did not know were to start so I made a little test project to properly debug this. Debugging learnt me that after setting the data binding of the detail view the combobox SelectedItem data binding still held a reference to the previous viewmodel and set the Country property on my viewmodel to null.

I could not think of an easy fix but all of the sudden I had a lucky hunch. I switched the ItemSource and SelectedItem in the combobox XAML like this:

<ComboBox SelectedItem="{Binding SelectedCountry}"
ItemsSource="{Binding Countries, Mode=OneWay}"
DisplayMemberPath="Name" >

And tada everything worked as it should ...

I do not have a clue why it is like that, it is a WPF bug I guess. I will try to report it somewhere. Attached is my test project that reproduces and fixes the problem. (19.44 kb)