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);

    }

}

Advertisements
This entry was posted in Silverlight. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s