绑定到 DataView 时如何删除 ListViewItem
当 ItemsSource 设置为 DataView 时,如何从 WPF ListView 中删除选定的 ListViewItem?我可以获得所选的 ListViewItem,然后如何删除 DataView 中的实际行?
DataView dv = (DataView)myListView.ItemsSource;
ListViewItem lvi = (ListViewItem)myListView.ItemContainerGenerator.ContainerFromItem(myListView.SelectedItem);
<Delete ListViewItem here>
How do I delete a selected ListViewItem from a WPF ListView when the ItemsSource is set to a DataView? I can get the ListViewItem that was selected and then how do remove the actual row in the DataView?
DataView dv = (DataView)myListView.ItemsSource;
ListViewItem lvi = (ListViewItem)myListView.ItemContainerGenerator.ContainerFromItem(myListView.SelectedItem);
<Delete ListViewItem here>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将集合绑定到列表视图时,请使用 ListCollectionView 而不是 DataView。可以像这样轻松完成(其中 dataView 是 DataView 类型):
现在,当您需要删除任何对象时,只需执行以下操作:
删除后,只需刷新视图:
或
When you bind your collection to the listview, use ListCollectionView instead of DataView. Can be easily done like this (where dataView is of type DataView):
Now when you need to delete any object, just do this:
And after deleting, just refresh the view:
or
考虑使用 MV-VM 模式来分离从数据对象列表中删除项目的概念,并直接从当前 UI 实现中删除它们。除了绑定之外,两者不需要互相了解。
当您使用 MVVM 模式时,请在 ViewModel 中公开布尔值“IsSelected”属性。
接下来,在您的视图中尝试如下操作:
这将允许您添加、编辑和删除 ViewModel 列表中的项目 - 就像它是实际的 ListView 一样。从这里,您还可以检查每个项目的 IsSelected(响应鼠标与 ListView 的交互),而无需实际检查 ListViewItem。这将是一个更干净、可维护的解决方案。
Consider using the M-V-VM pattern to separate the notion of removing an item from your list of data objects and DIRECTLY removing them from your current UI implementation. The two do not need to know about each other, aside from Bindings.
When you use the MVVM pattern, expose a boolean "IsSelected" property in your ViewModel.
Next, in your View try something like this:
This will let you add, edit, and remove items in your ViewModel's List -- just like if it were the actual ListView. From here, you can also check each item's IsSelected (that responds to mouse interactions with the ListView) without actually checking the ListViewItem. This will be a much cleaner, maintainable solution.