C# 设置组合框SelectedIndex

C# 设置组合框SelectedIndex,c#,wpf,combobox,C#,Wpf,Combobox,我有一个组合框,它有一个MyItem类的对象,这个类有一个string属性和一个integer属性 _myComboBoxItems = new List<MyItem>(); _myComboBoxItems.Add(new MyItem("stringId1",intId1)); _myComboBoxItems.Add(new MyItem("stringId2",intId2)); _myComboBoxItems.Add(new MyItem("stringId3",int

我有一个组合框,它有一个MyItem类的对象,这个类有一个string属性和一个integer属性

_myComboBoxItems = new List<MyItem>();
_myComboBoxItems.Add(new MyItem("stringId1",intId1));
_myComboBoxItems.Add(new MyItem("stringId2",intId2));
_myComboBoxItems.Add(new MyItem("stringId3",intId3));

MyCombo.ItemsSource = _myComboBoxItems;

我该怎么做?如何搜索_mycomboxItems的项目并获取与我传入的值匹配的项目。

您可以使用一些LINQ:

void ChangeSelectedItem(MyItem item)
{
    MyCombo.SelectedIndex = _myComboBoxItems.IndexOf(_myComboBoxItems.FirstOrDefault(x => x.intId == item.intId));
}
请注意,您最好设置组合框的
SelectedItem
属性:

void ChangeSelectedItem(MyItem item)
{
    MyCombo.SelectedItem = MyCombo.Items.OfType<MyItem>().FirstOrDefault(x => x.intId == item.intId);
}
void ChangeSelectedItem(MyItem)
{
MyCombo.SelectedItem=MyCombo.Items.OfType().FirstOrDefault(x=>x.intId==item.intId);
}
如果(collection[i].derp==true)muhCombo.SelectedIndex=i
void ChangeSelectedItem(MyItem item)
{
    MyCombo.SelectedItem = MyCombo.Items.OfType<MyItem>().FirstOrDefault(x => x.intId == item.intId);
}