简体   繁体   中英

Remove item from listbox

I am trying to remove an item from a listbox using C# code using the following line of code:

search_history.Items.RemoveAt(selected);

However I get the following message: Operation not supported on read-only collection.

What is the workaround solution for this problem other than resetting the listbox and entering the items all over again?

You should bind your ListBox to a ObservableCollection<T> , by setting the serach_history.ItemsSource = myObservableCollection

Then you can do myObservableCollection.Remove(search_history.SelectedItem) and the item will be removed from the collection, and the UI will update accordingly.

In general, you should always aim to use Data Bindings rather than add items directly to a collection.

search_history.Items.Remove(search_history.SelectedItem);

Item of the itemsource should implement the INotifyCollectionChanged interface. To simplify matters, you can use the ObservableCollection< T > instead of the List< T >. Then using the code shown below will work well:

(yourlistbox.ItemsSource as ObservableCollection<T>).RemoveAt(selected);

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM