[英]WPF: multiple foreground colors in a ComboBox
在XAML中,我们可以为ComboBox
每个项设置特定属性,例如:
<ComboBoxItem Foreground="Blue" Background="AntiqueWhite" Content="First Item"/>
<ComboBoxItem Foreground="Yellow" Background="Red" Content="Second Item"/>
当我从代码动态填充ComboBox
时尝试执行此操作时, ComboBox .Foreground
属性会在所有项目上设置前景值。 我想知道是否有任何方法可以在代码中实现这一点(为不同的项目设置不同的前景色)。
例如:
ComboBox1[First Item].Foreground = Brushes.Red;
ComboBox1[Second Item].Foreground = Brushes.Blue;
尝试将ComboBox的Item转换为ComboBoxItem
类型,然后设置它的Foreground
属性而不是整个ComboBox的Foreground
:
((ComboBoxItem)ComboBox1.Items[0]).Foreground = Brushes.Red;
更新:
如果您通过以下方式从代码向ComboBox1
添加新项:
ComboBox1.Items.Add(new ComboBoxItem {Content = "Third Item"});
转换将正常工作,因为上面的代码类似于你所展示的XAML对应代码。 但是如果你这样做的话:
ComboBox1.Items.Add("Third Item");
铸造不起作用。 因为该代码将字符串添加到ComboBox Item而不是ComboBoxItem对象。 在这种情况下,获取ComboBoxItem并不是那么简单,您需要使用ItemContainerGenerator
来获取它,如下所示:
var comboBoxItem = (ComboBoxItem)ComboBox1.ItemContainerGenerator.ContainerFromItem(ComboBox1.Items[0]);
comboBoxItem.Foreground = Brushes.Red;
试试这个:
XAML
<Grid>
<ComboBox Name="TestComboBox"
Width="100"
Height="30"
Loaded="TestComboBox_Loaded">
<ComboBoxItem Content="First Item"/>
<ComboBoxItem Content="Second Item"/>
</ComboBox>
</Grid>
Code-behind
private void TestComboBox_Loaded(object sender, RoutedEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null)
{
var firstItem = comboBox.Items[0] as ComboBoxItem;
var secondItem = comboBox.Items[1] as ComboBoxItem;
if (firstItem != null && secondItem != null)
{
firstItem.Foreground = Brushes.Red;
secondItem.Foreground = Brushes.Blue;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.