How to change combobox particular item color dynamically in wpf

c#, combobox, wpf

Solution

Instead of adding the actual value of `i` in the combobox, add a `ComboBoxItem` instead:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            ComboBoxItem item = new ComboBoxItem();

            if (i == 2) item.Foreground = Brushes.Blue;
            else item.Foreground = Brushes.Pink;

            item.Content = i.ToString();
            com_ColorItems.Items.Add(item);
        }
    }

If you want to modify the ComboBoxItem created with this method later, this is how you can do it:

var item = com_ColorItems.Items[2] as ComboBoxItem; // Convert from Object
if (item != null)                                   // Conversion succeeded 
{
    item.Foreground = Brushes.Tomato;
}

Problem

``` <Grid x:Name="LayoutRoot"> <ComboBox x:Name="com_ColorItems" Height="41" Margin="198,114,264,0" VerticalAlignment="Top" FontSize="13.333" FontWeight="Bold" Foreground="#FF3F7E24"/> </Grid> ``` With above code I colored all items in the combobox green. ``` private void Window_Loaded(object sender, RoutedEventArgs e) { for (int i = 0; i < 5; i++) { com_ColorItems.Items.Add(i); } } ``` With above code I have filled five items into combobox. Now I like to change the color of the 3rd item (3) to "red" in code behind dynamically. How can I do that?

Original source