The better solution is to add related attributes to your item model e.g. a IsUserSelected
property. Then create a Style
, which you assign to ItemsControl.ItemContainerStyle
. Inside this Style
you define a trigger that triggers on IsUserSelected
.
That's how it is done. Don't deal with the generator and check if each item is generated. Let the framework do this work for you.
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding IsUserSelected}"
Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>`enter code here`
</ListBox>
Since you already have a property HighlightId
in your code-behind file, you can use a IMultiValueConverter
together with a MultiBinding
to define a color based on the value:
MainWindow.xaml.cs
partial class MainWindow
{
public static readonly DependencyProperty HighlightIdProperty = DependencyProperty.Register(
"HighlightId",
typeof(int),
typeof(MainWindow),
new PropertyMetadata(default(int)));
public int HighlightId
{
get => (int) GetValue(MainWindow.HighlightIdProperty);
set => SetValue(MainWindow.HighlightIdProperty, value);
}
}
HighlightIdToBrushConverter.cs
public class HighlightIdToBrushConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (!(values[0] is MyModelType currentItem
&& values[1] is int highlightId))
{
return Binding.DoNothing;
}
var highlightBrush = highlightId == currentItem.Id
? new SolidColorBrush(Colors.Red)
: new SolidColorBrush(Colors.Transparent);
highlightBrush.Freeze();
return highlightBrush;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
}
MainWindow.xaml
<ListBox ItemsSource="{Binding Items}">
<ListBox.Resources>
<HighlightIdToBrushConverter x:Key="HighlightIdToBrushConverter" />
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource HighlightIdToBrushConverter}">
<Binding />
<Binding RelativeSource="{RelativeSource AncestorType=Window}"
Path="HighlightId" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>