Description
In Picker.cs, when we close a popup dialog that contains a picker control inside the "SelectedIndexChanged" event, the Items collection has 0 elements and a SelectedIndex is still set. (This can occur when some portion of the code sets the BindingContext to null)
Under these conditions, we get an argument out of range exception within the UpdateSelectedItem() method on line 215:
void UpdateSelectedItem()
{
if (SelectedIndex == -1) {
SelectedItem = null;
return;
}
if (ItemsSource != null) {
SelectedItem = ItemsSource [SelectedIndex];
return;
}
SelectedItem = Items [SelectedIndex]; //Line 215
}
Steps to Reproduce
- Set up a Picker control in a popup dialog
- In the SelectedIndexChanged event, set the BindingContext to null when the last element in the picker is chosen
- In the SelectedIndexChanged event close the popup when the last element in the Picker is chosen
- Run the code
- Select the last element
- Index out of bounds exception on line 215 of Picker.cs
Expected Behavior
I would expect there to be a check on line 215 of the Picker.cs that does not allow choosing an item by index value when there aren't any elements in the list.
Actual Behavior
Throws exception, app bombs
Reproductions
Picker picker = new Picker();
picker.ItemsSource = new List<string> { "cat", "mouse", "rabbit" };
picker.SelectedIndexChanged += (_, __) =>
{
picker.ItemsSource = null;
};
return new ContentPage()
{
Content = picker
};
https://github.com/xamarin/Xamarin.Forms/files/2036809/ExceptionExample.zip