Yellow
Yellow

Reputation: 3957

Finding the index of a ComboBoxItem in a WPF Combobox

I added a SelectionChanged event 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:

// 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 ComboBoxItem just have an Index property?

Upvotes: 0

Views: 8279

Answers (1)

sexta13
sexta13

Reputation: 1568

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);
    }

Upvotes: 3

Related Questions