开发者

How does ListView.ItemCollection.Contains() work?

I'm copying ListViewItems from one ListView to another, sth. like:

foreach (ListViewItem item in usersListView.SelectedItems) {
    selectedUsersListView.Items.Add((ListViewItem)item.Clone());
}

If I want to use ListView.ItemCollection.Contains() to determine if an item was already copied I always get false:

foreach (ListViewItem item in usersListView.SelectedItems) {
    if (!selectedUsersListView.Items.Contains(item) { // always !false
        selectedUsersListView.Items.Add((ListViewItem)item.Clone());
    }
}

I did the following to solve my problem:

foreach (ListViewItem item in usersListView.SelectedItems) {
    ListViewItem newItem = (ListViewItem)item.Clone();
    newItem.Name         = newItem.Text;

    if (!selectedUsersListView.Items.ContainsKey(newItem.Name) { // this works
        selectedUsersListView.Items.Add(n开发者_如何学编程ewItem);
    }
}

So, it's ok that this solves my problem but I still have no idea why ListView.ItemCollection.Contains() doesn't work...

How does ListView.ItemCollection.Contains() identify if an item already exists?

How do ListViewItems have to be initialised that ListView.ItemCollection.Contains() (not ListView.ItemCollection.ContainsKey()) is able to identify them?


Internally ListViewItemCollection uses the == operator to test for equality. Since ListViewItem does not override the == operator, ListViewItemCollection.Contains compares references. Since you are cloning your ListViewItems, your call to Contains will always return false because you are comparing two different object references.

Edit:

You cannot add the same ListViewItem to two different ListViews so what you are trying to do is not possible using Contains. You need to use ContainsKey. In the following example Contains will return true:

var item = new ListViewItemEquality("Item1");
listView1.Items.Add(item1);
Debug.Assert(listView1.Items.Contains(item1));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜