ComboBox’s SelectedItem not Displaying

August 20, 2011

I see a lot of posts on StackOverflow about WPF ComboBoxes not displaying the SelectedItem correctly.

The code given usually looks something like this:

<ComboBox ItemsSource="{Binding MyList}"
          SelectedItem="{Binding MyItem}" />

The problem is simple: By default WPF compares SelectedItem to each item in the ItemsSource by reference, meaning that unless the SelectedItem points to the same item in memory as the ItemsSource item, it will decide that the item doesn’t exist in the ItemsSource and so no item gets selected.

To work around this, you can either use the ComboBox’s SelectedValue and SelectedValuePath to set the SelectedItem by Value instead of by Item

<ComboBox ItemsSource="{Binding MyList}"
          SelectedValue="{Binding SelectedId}" />

Or you can overwrite the .Equals() method of the MyItem class so that it returns true if two item’s have the same data, not just the same memory reference.

public override bool Equals(object obj) 
    if (obj == null || !(obj is MyClass)) 
        return false; 
    return ((MyClass)obj).Id == this.Id);