Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change combobox particular item color dynamically in wpf

Tags:

c#

combobox

wpf

<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?

like image 425
ASHOK A Avatar asked Jun 30 '12 05:06

ASHOK A


2 Answers

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;
}
like image 151
Tibi Avatar answered Sep 21 '22 15:09

Tibi


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

like image 21
Mario Binder Avatar answered Sep 22 '22 15:09

Mario Binder