How to dynamically change the color of an item list item in 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 the code above, I colored all the elements in the green combo box.

 private void Window_Loaded(object sender, RoutedEventArgs e) { for (int i = 0; i < 5; i++) { com_ColorItems.Items.Add(i); } } 

With the code above, I populated five elements in a combobox. Now I like to dynamically change the color of the 3rd element (3) to "red" in the code. How can i do this?

+7
source share
2 answers

Instead of adding the actual value of i to the combo box, 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 change the ComboBoxItem created using this method later, here 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; } 
+10
source

First try linking your source and avoiding direct access through the code behind. And how can you use the converter in an ItemSource binding.

eg.

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

and in your converter find the third item and give them another ForegroundColor

+1
source

All Articles