Cannot remove StackPanel by name from list in C #

I am trying to remove an item from a ListBox using the following code:

 listBox.Items.Remove(stackPanelName); 

I am not getting any errors, but also not getting any visible results.

Does anyone know what I'm doing wrong?

+4
source share
2 answers

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 the listBox.Items collection listBox.Items not have an item with this name. You might want to do this more safely:

 var stackPanelItem = listBox.Items.OfType<FrameworkElement>() .FirstOrDefault(x => x.Name == stackPanelName); if (stackPanelItem != null) { listBox.Items.Remove(stackPanelItem); } 
+1
source

I would not recommend directly deleting items from the ListBox (I'm surprised that the error does not occur, since listBox.Items returns a read-only collection, so calling Remove on it is not possible if I'm not mistaken). In any case, you should focus on managing your backup collection.

For example, if you save your objects in an ObservableCollection , it automatically notifies the user interface (ListBox in this case) that the item has been deleted and updates the user interface for you. This is because the ObservableCollection implements the INotifyPropertyChanged and INotifyCollectionChanged by default, so when something in the collection changes, it fires an event that reports an update to the user interface control.

+1
source

Source: https://habr.com/ru/post/1495125/


All Articles