How to remove items from a bound list box or how to avoid “Operation not supported on read-only collection.”

Today I got a rude error message from my application when I attempted to do a very simple operation, that of removing an item from ListBox; "Operation not supported on read-only collection."

The problem stems from the fact that I’d bound my ListBox to an ObservableCollection, once bound the Items collection becomes read-only. A know some others have had the same problem so I thought I’d blog about my solution.  Utilizing a function, I’d previously blogged about, to find the ListBoxItem from a button click I then do a little casting and the item is removed;

private void buttonDelete_Click(object sender, RoutedEventArgs e)

{

    ListBoxItem selectedItem = FindAssociatedListBoxItem(sender);

 

    // if we have found an item then remove it

    if (selectedItem != null)

    {               

        MyColl myColl = this.ListBoxProducts.ItemsSource as MyColl;

        MyObject selectedObj = selectedItem.DataContext as MyObject;

        myColl.Remove(selectedObj);

    }

}

Leave a comment