我有一个ComboBox,它有一个MyItem类的对象,它有一个字符串属性和一个整数属性。
_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;现在,我希望基于传递给我的函数的一个_myComboBoxItems SelectedIndex对象来设置MyItem对象。
void ChangeSelectedItem(MyItem item)
{
MyCombo.SelectedIndex = find the index of the _myComboBoxItems that has an intId of e.g. item.intId
}我该怎么做?如何搜索_myComboBoxItems的项并获取具有与传入的值相匹配的值的项。
发布于 2017-02-27 17:07:59
您可以使用LINQ:
void ChangeSelectedItem(MyItem item)
{
MyCombo.SelectedIndex = _myComboBoxItems.IndexOf(_myComboBoxItems.FirstOrDefault(x => x.intId == item.intId));
}请注意,您最好设置SelectedItem属性的ComboBox
void ChangeSelectedItem(MyItem item)
{
MyCombo.SelectedItem = MyCombo.Items.OfType<MyItem>().FirstOrDefault(x => x.intId == item.intId);
}那么您就不需要在List<T>中找到索引了。
https://stackoverflow.com/questions/42491509
复制相似问题