如何获取 WPF 列表框中所选项目的索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16689029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:50:45  来源:igfitidea点击:

How to get indices of selected items in WPF's listbox?

c#wpflistboxindexingselection

提问by Spook

Before you mark this question as a duplicate or suggest using Items.IndexOf, please do the following:

在将此问题标记为重复或建议使用 Items.IndexOf 之前,请执行以下操作:

public MainWindow()
{
    InitializeComponent();

    var A = new object();
    var B = new object();
    var C = new object();

    lbItems.Items.Add(A);
    lbItems.Items.Add(B);
    lbItems.Items.Add(C);
    lbItems.Items.Add(A);
    lbItems.Items.Add(B);
    lbItems.Items.Add(C);
}

private void lbItems_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show(lbItems.Items.IndexOf(lbItems.SelectedItems[0]).ToString());
}

Then doubleclick fourth element (you'll get 0 instead of 3).

然后双击第四个元素(你会得到 0 而不是 3)。

How to get a list of selected item indices?

如何获取所选项目索引的列表?

采纳答案by Dan Puzey

This is caused by you adding the same object to the list twice. The ListBoxcontrol can't tell between them. One way around this problem is to wrap each item in another class:

这是由于您将同一对象添加到列表两次造成的。该ListBox控制不能在它们之间说不清。解决此问题的一种方法是将每个项目包装在另一个类中:

lbItems.Items.Add(new WrappedThing((a));
lbItems.Items.Add(new WrappedThing((b));
lbItems.Items.Add(new WrappedThing((a));
lbItems.Items.Add(new WrappedThing((b));

... which means that each item in the list is unique, even though the item they're wrapping may not be. Note that any data template or bindings would also have to change to support this, though you could do this with a single global DataTemplate.

...这意味着列表中的每个项目都是唯一的,即使它们包装的项目可能不是。请注意,任何数据模板或绑定也必须更改以支持这一点,尽管您可以使用单个全局DataTemplate.

WrappedThingwould look something like this:

WrappedThing看起来像这样:

class WrappedThing<T>
{
    public WrappedThing(T thing)
    {
        Thing = thing;
    }

    public T Thing { get; private set; }
}

(Note: this is copied from my answer to a different question heresince the answer is useful but the question is slightly different.)

(注意:这是从我在这里对另一个问题的回答中复制的,因为答案很有用,但问题略有不同。)

回答by Sayse

Further to my comment (" its getting the first index of object A which is 0"),

进一步我的评论(“它获得对象 A 的第一个索引是 0”),

int j = 0;
for (int i = 0; i < lbItems.Items.Count; i++)
{
    if (lbItems.Items[i] == lbItems.SelectedItems[0])
      j++;
}
MessageBox.Show(lbItems.Items.IndexOf(lbItems.SelectedItems[0]).ToString()
+ string.Format("\r\nThere are {0} occurences of this object in this list", j));