<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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With