如何在 WPF 中以编程方式清除所有项目的列表框?
How to clear a listbox of all items programatically in WPF?
我正在尝试清除重置和禁用表单字段的函数中的列表框。
我查过的所有论坛都说要用:
listBox.Items.Clear();
但是这会抛出一个异常:
'Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.'
如有任何想法,我们将不胜感激!
您似乎将列表框的 ItemsSource 属性 绑定到某个集合。只需清除集合的内容即可。如果它是一个 ObservableCollection,列表框将被自动清除,否则实现 INotifyPropertyChanged 模式。
像这样声明要绑定的列表:
public ObservableCollection<MyType> ListboxItems { get; set; }
然后您可以使用
清除列表
ListBoxItems.Clear();
我正在尝试清除重置和禁用表单字段的函数中的列表框。
我查过的所有论坛都说要用:
listBox.Items.Clear();
但是这会抛出一个异常:
'Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.'
如有任何想法,我们将不胜感激!
您似乎将列表框的 ItemsSource 属性 绑定到某个集合。只需清除集合的内容即可。如果它是一个 ObservableCollection,列表框将被自动清除,否则实现 INotifyPropertyChanged 模式。
像这样声明要绑定的列表:
public ObservableCollection<MyType> ListboxItems { get; set; }
然后您可以使用
清除列表ListBoxItems.Clear();