I'm trying to create a dialog with a dynamic combobox that changes the colour of the items' text depending on what is other comboboxes have as their selected items. I've done this by having the combobox's dropdownopened event start a loop which tests each comboboxitem's value against the selected value of the other combobox, changing the colour depending on whether it's greater or smaller.
It mostly works using ComboBox.ItemContainerGenerator to customise the comboboxitems directly, but it doesn't update the colours until the second time the combobox is opened.
I've recreated this problem with much simpler comboboxes:
XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DisposableXAML"
xmlns:Properties="clr-namespace:DisposableXAML.Properties"
x:Class="DisposableXAML.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="306" Width="396">
<Canvas>
<ComboBox x:Name="combobox1" Canvas.Left="129" Canvas.Top="44" Width="120" SelectedIndex="0"/>
<ComboBox x:Name="combobox2" Canvas.Left="129" Canvas.Top="117" Width="120" DropDownOpened="combobox2_DropDownOpened"/>
</Canvas>
</Window>
C#:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace DisposableXAML
{
public partial class MainWindow : Window
{
List<int> intList;
public MainWindow()
{
InitializeComponent();
DataContext = this;
intList = new List<int>() { 1, 2, 3, 4 };
combobox1.ItemsSource = intList;
combobox2.ItemsSource = intList;
}
private void combobox2_DropDownOpened(object sender, EventArgs e)
{
int SelectedNum = (int) combobox1.SelectedItem;
for (int i = 0; i < 4; i++)
{
ComboBoxItem item = (ComboBoxItem)combobox2.ItemContainerGenerator.ContainerFromIndex(i);;
if (item != null)
{
if (i < SelectedNum)
{
item.Background = Brushes.Green;
}
else
{
item.Background = Brushes.Blue;
}
}
}
}
}
}
Combobox on first open:

Combobox on second open:

Is there some way to get the combobox to update on the first open? Or is there a cleaner way I can achieve this effect?
ItemContainerStylein the XAML with triggers would be a far better choice. With XAML, stuff like this is almost always best done in the XAML. - 15ee8f99-57ff-4f92-890c-b56153