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

本文关键字:组合 索引 WPF 查找 | 更新日期: 2023-09-27 18:35:39

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

// 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! */;
    }
}

在此处检索正确索引的最简单方法是什么?为什么ComboBoxItem没有Index属性?

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

你能试试这样的事情吗:

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