If I change the ItemsSource property of a ListBox while an item is selected I get IndexOutOfRange exception because SelectedIndex property is set when an item is selected. If no item is selected in the ListBox exception is not raised but even if I set the SelectedItem property to null before changing the ItemsSource the exception still occurs if an item was selected because SelectedIndex property still has a value.
Is there a solution or a workaround for this problem?
Edit: Here is the sample code because this problem only occurs if I apply a Contains filter in my LINQ to objects expression AND an item is selected in the ListBox… MyList is a List<> of CLR objects…
lstMyList.ItemsSource = MyList.Where(i => i.TypeId == 1);
That works fine. This modified LINQ query also works fine (if no item is selected) but if an item is selected I get IndexOutOfRangeException
lstMyList.ItemsSource = MyList.Where(i => i.TypeId == 1 && i.DisplayName.Contains(someString));
If I redirect this LINQ query to a var or a list of CLR objects the query works fine but when I try to make it an ItemsSource of my ListBox I get the exception (even if I make this var or a list of CLR object ItemsSource of my ListBox instead).
Just set
SelectedIndexto -1EDIT: OK, try that instead: