Wednesday, July 24, 2013

Fixing SelectedItem must always be set to a valid value

In the Windows Phone app I'm currently working on, I kept getting an "SelectedItem must always be set to a valid value" exception from a ListPicker on the OnSelectedItemChanged event.  It wasn't happening every time, but often enough that it was driving me crazy!

My collection consisted of fairly simple objects for the user to choose from, and I had a view model property for binding to the selected item.  The underlying issue is that it wasn't recognizing the selected item (in the binding) as a member of its list in ItemsSource property.  It turns out that it was a really simple fix.  By simply overriding the Equals method, my problems went away.  This enabled the control to see the selected item as equal to an item in the list.

If you've never done this before, you just need to add a method in the class to compare some key property, like this:

public override bool Equals(object obj)
{
    var other = obj as ThisClass;
    if( other == null ) return false;
    else return (this.SomeProperty == other.Property);
}

That's it!  Customize as needed, and you'll be good to go!