【发布时间】:2018-01-31 09:40:04
【问题描述】:
我有一个使用带有背景颜色的 ComboBoxItems 而不是 <System:String> 的组合框。
<ComboBox x:Name="cboColors"
HorizontalAlignment="Right"
Margin="0,135,212,0"
VerticalAlignment="Top"
Width="103">
<ComboBoxItem Background="White" Foreground="Black" Content="White"/>
<ComboBoxItem Background="Gray" Foreground="White" Content="Gray"/>
<ComboBoxItem Background="#FF262626" Foreground="White" Content="Dark Gray"/>
<ComboBoxItem Background="Black" Foreground="White" Content="Black"/>
<ComboBoxItem Background="#FFfdfd02" Content="Yellow"/>
<ComboBoxItem Background="#FF9aafe4" Content="Blue"/>
<ComboBoxItem Background="#FFffb0b0" Content="Pink"/>
</ComboBox>
我可以像这样得到ComboBoxItem的值
ComboBoxItem selectedItem = (ComboBoxItem)(mainwindow.cboColors.SelectedValue);
string selected = (string)(selectedItem.Content);
如何使用字符串"Yellow"设置 ComboBox SelectedItem?
cboColors.SelectedItem = "Yellow";
组合框不会改变。
【问题讨论】:
-
您需要使用字符串来识别ItemSource(组合框项)中的哪个对象成为选中项。即 cboColors.SelectedItem = cboColors.Items.FirstOrDefault(item => item.Content.Equals("Yellow"));
-
@CodexNZ 它给出错误,“ItemCollection 不包含 'FirstOrDefault' 的定义”。
-
为什么你回到硬编码的 xaml 对象而不是一个类来表示你的组合中的项目?此处提供的答案:stackoverflow.com/questions/45703106/… 将允许您使用绑定集合作为查找的源,而无需执行您正在尝试的操作。您需要做的就是为您的 ComboItem 类添加属性以进行背景和前景绑定。
标签: c# wpf visual-studio combobox