我有以下内容Combobox:
<ComboBox x:Name="Colors" FontSize="20">
<ComboBoxItem Background="#46d6db" Tag="#46d6db">Blue</ComboBoxItem>
<ComboBoxItem Background="#FDB75B" Tag="#FDB75B">Orange</ComboBoxItem>
<ComboBoxItem Background="#51B749" Tag="#51B749">Green</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
现在您可以看到我有三个具有特定Tag属性的 ComboBoxItem。这里的标签属性就是颜色的值。
我需要知道的是:如何通过 Tag 属性获取特定 ComboBoxItem 的索引?
我将尝试更清楚地解释它:假设我有一个名为colorvalue 的字符串#FDB75B,现在我需要找到具有相同值的 ComboBox 项,并特别Tag获取 this 的位置。ComboBoxItem
string color = "#FDB75B";
//In this way I get the Tag property of the selected item
((ComboBoxItem)Colors.SelectedItem).Tag.ToString();
Run Code Online (Sandbox Code Playgroud)
现在我需要做相反的情况,找到ComboBoxItem带有标签的索引#FDB75B,并自动选择它,如下:
Colors.SelectedIndex = "element found";
Run Code Online (Sandbox Code Playgroud)
这可能吗?
小智 5
使用 linq 查询并找出答案。这是一个示例代码
var selectedItem = Colors.Items
.Cast<ComboBoxItem>()
.Where(e => e.Tag.ToString() == "#FDB75B")
.FirstOrDefault();
Colors.SelectedItem = selectedItem;
Run Code Online (Sandbox Code Playgroud)