简体   繁体   中英

WPF: multiple foreground colors in a ComboBox

In XAML we can set specific properties for each item in a ComboBox , for example:

<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. 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 :

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

UPDATE :

if you add new item to ComboBox1 from code this way :

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. 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. In this case getting ComboBoxItem is not as straightforward, you'll need to get it using ItemContainerGenerator as follow :

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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