Bug in WPF combobox databinding

Last week we experienced an annoying bug in the WPF combobox databinding. One of the forms that we were 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 SelectedItem="{Binding SelectedCountry}"
          ItemsSource="{Binding Countries, Mode=OneWay}"

The bug we 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 our viewmodel was always set to null so the contact person's country was lost. We did not know where to start so we made a little test project to properly debug this. Debugging learnt us 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 our viewmodel to null.

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

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

And tada everything worked as it should ...

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

Download the project