How to change combobox particular item color dynamically in wpf

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

First, try to bind your Source and avoid the directly access through code behind. And than you can use an Converter in your ItemSource Binding.

e.g.

ItemSource={Binding MyComboboxItems, Converter={StaticResource MyConverter}}

and in your Converter find you the 3rd Item and give them a different ForegroundColor

Tags:

C#

Wpf

Combobox