简体   繁体   English

WPF:ComboBox中的多个前景色

[英]WPF: multiple foreground colors in a ComboBox

In XAML we can set specific properties for each item in a ComboBox , for example: 在XAML中,我们可以为ComboBox每个项设置特定属性,例如:

<ComboBoxItem Foreground="Blue" Background="AntiqueWhite" Content="First Item"/>
<ComboBoxItem Foreground="Yellow" Background="Red" Content="Second Item"/>

When I try to do this when I'm dynamically filling a ComboBox from code, the ComboBox .Foreground property sets a foreground value on all the items. 当我从代码动态填充ComboBox时尝试执行此操作时, ComboBox .Foreground属性会在所有项目上设置前景值。 I would like to know if there's anyway to achieve this (setting different foreground colors for different items) in the code. 我想知道是否有任何方法可以在代码中实现这一点(为不同的项目设置不同的前景色)。

For example: 例如:

ComboBox1[First Item].Foreground = Brushes.Red;
ComboBox1[Second Item].Foreground = Brushes.Blue;

Try to cast ComboBox's Item to ComboBoxItem type, then set it's Foreground property instead of the whole ComboBox's Foreground : 尝试将ComboBox的Item转换为ComboBoxItem类型,然后设置它的Foreground属性而不是整个ComboBox的Foreground

((ComboBoxItem)ComboBox1.Items[0]).Foreground = Brushes.Red;

UPDATE : 更新:

if you add new item to ComboBox1 from code this way : 如果您通过以下方式从代码向ComboBox1添加新项:

ComboBox1.Items.Add(new ComboBoxItem {Content = "Third Item"});

casting will work fine, because the code above resemble it's XAML counterpart you showed in question. 转换将正常工作,因为上面的代码类似于你所展示的XAML对应代码。 But if you did it this way instead : 但是如果你这样做的话:

ComboBox1.Items.Add("Third Item");

casting won't work. 铸造不起作用。 Because that code added string to ComboBox Item instead of ComboBoxItem object. 因为该代码将字符串添加到ComboBox Item而不是ComboBoxItem对象。 In this case getting ComboBoxItem is not as straightforward, you'll need to get it using ItemContainerGenerator as follow : 在这种情况下,获取ComboBoxItem并不是那么简单,您需要使用ItemContainerGenerator来获取它,如下所示:

var comboBoxItem = (ComboBoxItem)ComboBox1.ItemContainerGenerator.ContainerFromItem(ComboBox1.Items[0]);
comboBoxItem.Foreground = Brushes.Red;

Try this: 试试这个:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM