在 WPF 组合框中查找 ComboBoxItem 的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19400913/
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 09:52:24  来源:igfitidea点击:

Finding the index of a ComboBoxItem in a WPF Combobox

c#wpfcombobox

提问by Yellow

I added a SelectionChangedevent to my ComboBox, and I need to find the index of the previous selected item. I can't find a simple way to find the item index, though. I've got:

SelectionChanged在我的 ComboBox 中添加了一个事件,我需要找到上一个所选项目的索引。但是,我找不到找到项目索引的简单方法。我有:

// In the XAML file
<ComboBox Name="myCombobox" ItemsSource="{Binding MyCollectionView}" SelectionChanged="myCombobox_SelectionChanged" />


// In the XAML.cs file
public void myCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBoxItem item = e.RemovedItems[0];
    if (e.AddedItems.Count > 0)
    {
        ComboBoxItem item = e.RemovedItems[0];
        if (item != null)
            int index = /* Find index of this item! */;
    }
}

What is the easiest way to retrieve the correct index here? Why doesn't the ComboBoxItemjust have an Indexproperty?

在这里检索正确索引的最简单方法是什么?为什么不ComboBoxItem只是拥有Index财产?

回答by sexta13

Can you try something like this:

你可以尝试这样的事情:

Combobox comboBox = sender as ComboBox;

 if (e.AddedItems.Count > 0)
    {
        ComboBoxItem item = e.RemovedItems[0];
        if (item != null)
            int index = combobox.Items.IndexOf(item);
    }