WPF:SelectedItems使用重复的对象引用 [英] WPF: SelectedItems with duplicate object references

查看:104
本文介绍了WPF:SelectedItems使用重复的对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以可以说我有这些类:

So lets say I have these classes:

public class Person
{
     public string Name { get; set; }
}
public class PersonCollection : ObservableCollection<Person> { }

和可以说我有一个ListView的的ItemsSource绑定到一个PersonCollection。现在让我们说我有这样的code:

And lets say I have a ListView whose ItemsSource is bound to a PersonCollection. Now lets say I have this code:

public void AddPeople()
{
     Person p = new Person() { Name = "Someone" };
     MyPersonCollection.Add(p);
     MyPersonCollection.Add(p);
     MyPersonCollection.Add(p);
}

所以,现在我有三个项目,其中三个项目是对同一个对象引用一个ListView。所以现在我选择可以说与在ListView指数0和2项。

So now I have a ListView with three items in which all three items are references to the SAME object. So now I select lets say items with index 0 and 2 in the ListView.

该ListView.SelectedItems财产会说我选择了一个项目,因为两者在视觉上选定的项目是同一对象。

The ListView.SelectedItems property will say I have ONE item selected since both visually selected items are the SAME object.

因此​​,如何,我可以得到视觉上选定的项目,所以我可以删除在索引0和2的项目,没有索引1拆除项目?

So how can I get the visually selected items so I can remove the items at indices 0 and 2, without removing the item at index 1?

推荐答案

在的WinForms还有就是 ListBox.SelectedIndices 属性,在这里很有用,但我们不这样做有在WPF,可惜......

In WinForms there is the ListBox.SelectedIndices property that would be useful here, but we don't have that in WPF, unfortunately...

您可以通过 ListViewItem的 s,使用<一个迭代href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcontainergenerator.containerfromindex.aspx\"相对=nofollow> ItemContainerGenerator.ContainerFromIndex ,检查的 ListViewItem.IsSelected ,然后通过索引中删除它们。但是,这并不虚拟化技术发挥好,因为 ContainerFromIndex 如果您滚动从项目远离可能返回null,它就会被虚拟化的。

You could iterate through the ListViewItems using ItemContainerGenerator.ContainerFromIndex, check ListViewItem.IsSelected and then remove them by index. However, this doesn't play well with virtualization because ContainerFromIndex could return null if you scroll away from the item and it gets virtualized.

在code会是这个样子:

The code would look something like this:

for(int ixPerson = myListView.Items.Count - 1; ixPerson >= 0; ixPerson--)
{
   ListViewItem personItem = myListView.ItemContainerGenerator.ContainerFromIndex(ixPerson);
   if (personItem.IsSelected)
   {
      mySourcePersonCollection.RemoveAt(ixPerson);
   }
}

这篇关于WPF:SelectedItems使用重复的对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆