c# - 从 WPF 绑定(bind)列表框中删除项目

标签 c# wpf binding listbox itemssource

我有一个带有 ListBox(称为 listMyItems)的 WPF 应用程序,它已成功绑定(bind)到我创建的 MyItems 类。我有一个名为 currentMyItems 的 MyItems 列表,然后将其作为 ItemSource 分配给 ListBox。一切正常,如果我将一个项目添加到 currentMyItems 它会弹出列表等。 当我尝试删除 ListBox 中的所选项目时出现问题。这是我使用的代码:

currentMyItems.Remove((MyItem)listMyItems.SelectedItem);

该项目从 ListBox 中消失,但下次我更新它时,它又弹出来,因为它从未被删除。有什么建议吗?

最佳答案

我想您可能对数据绑定(bind)的工作原理感到困惑。当您绑定(bind)一个属性时,您是在告诉 WPF 去其他地方寻找该属性的值。

当您绑定(bind) ListBox.ItemsSource 时属性(property)currentMyItems ,你告诉 WPF 去看看 currentMyItems列表以查找其项目列表。如果currentMyItems是一个 ObservableCollection而不是 List<T> ,然后当您从集合中添加或删除项目时,UI 将自动收到更新绑定(bind)值的通知。

根据您在问题中所说的内容,听起来您有两个集合,其中一个是绑定(bind)的,另一个用于在发生更改时重新创建第一个集合。所有这些都不需要。

只需创建一个 ObservableCollection<MyItem> , 将其绑定(bind)到 ListBox.ItemsSource属性,然后从该单个集合中添加或删除项目。它应该像您预期的那样工作。

<ListBox x:Name="listMyItems" ItemsSource="{Binding MyItems}" />

MyItems.Add((MyItem)listMyItems.SelectedItem)
MyItems.Remove((MyItem)listMyItems.SelectedItem)

如果您有兴趣,我的博客上还有一些初学者文章,供难以理解 DataContext 的 WPF 用户使用。您可能想查看 Understanding the change in mindset when switching from WinForms to WPFWhat is this “DataContext” you speak of?

关于c# - 从 WPF 绑定(bind)列表框中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19937927/

相关文章:

c# - 将 View 模型中的 ObservableCollection 绑定(bind)到列表框

java - JTable中selectedElements的个数可以绑定(bind)吗?

c# - 错误 : Conversion failed when converting date and/or time from character string

c# - Windows Phone 8 加速度计事件

c# - 如何将绑定(bind)添加到数据网格中的列?

c# - WPF 是否将全尺寸图像嵌入到输出中?

javascript - _this3.state.method 不是函数

c# - ElasticSearch-使用对象初始化API构建多个聚集的.NET NEST API似乎创建了错误的请求

c# - 在电子邮件中编码为 UTF-8

c# - WPF 使用 MVVM : DataBinding with RelativeSource