Reputation: 2026
<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?
Upvotes: 7
Views: 13291
Reputation: 2868
In addition to Mario Binders answer, here an example of such a converter:
public class ListToColoredComboboxItemsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is IEnumerable<Measurement> measurements)
{
var comboBoxItems = new List<ComboBoxItem>(measurements.Count());
foreach (var measurement in measurements)
{
var item = new ComboBoxItem();
item.Content = measurement;
if (!string.IsNullOrWhiteSpace(measurement.ErrorMessage))
item.Foreground = Brushes.Red;
comboBoxItems.Add(item);
}
return comboBoxItems;
}
return null;
}
public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And probably you also want to convert the selected Item back to a value:
public class ComboBoxItemToItemConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
{
if (value is ComboBoxItem comboBoxItem)
{
return comboBoxItem.Content;
}
return null;
}
}
Upvotes: 1
Reputation: 1623
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
Upvotes: 2
Reputation: 3875
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;
}
Upvotes: 11