Reputation: 1180
I'm trying to remove an item from a ListBox
using the following code:
listBox.Items.Remove(stackPanelName);
I don't get any errors, but neither do I get any visible results.
Does anyone know what I am doing wrong?
Upvotes: 4
Views: 122
Reputation: 69372
I wouldn't recommend trying to remove items from the ListBox directly (I'm surprised an error isn't thrown as listBox.Items
returns a read-only collection so calling Remove
on it shouldn't be possible, unless I'm mistaken). Either way, you should be focusing on managing the backing collection.
For example, if you store your items in an ObservableCollection it will automatically notify the UI (ListBox in this case) that an item was removed and will update the UI for you. This is because ObservableCollection
implements the INotifyPropertyChanged
and INotifyCollectionChanged
interfaces by default and so when something in the collection changes, it's fires an event that tells the UI control to update.
Upvotes: 1
Reputation: 149030
You can do something like this:
var stackPanelItem = listBox.Items.OfType<FrameworkElement>()
.First(x => x.Name == stackPanelName);
listBox.Items.Remove(stackPanelItem);
This will fail if there is no item with that name in the listBox.Items
collection. You might want to do this to be a bit safer:
var stackPanelItem = listBox.Items.OfType<FrameworkElement>()
.FirstOrDefault(x => x.Name == stackPanelName);
if (stackPanelItem != null)
{
listBox.Items.Remove(stackPanelItem);
}
Upvotes: 1