I want to change the background/hightlight color of a selected ListBox item using data binding. This is what I have and tried, but it's not working. I'm not sure how to get the resources section to have the "current item" context.
Color is a property on every item displayed (and has a different value for each item).
<ListBox x:Name="Categorie" ItemsSource="{Binding Categories}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding /Color}" />
</Style.Resources>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding /Color}" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Center"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Best Answer
You can use a
Trigger
to achieve that:Note that for this binding to work, you must have a property called
Color
on the data item objects that are set as theListBox.ItemsSource
.UPDATE >>>
Ok, so that was my bad... I forgot that
SolidColorBrush
is not aFrameworkElement
and isFreezable
, so they cannot be used in aBinding
... you have a few options:Either create your colour(s) as
StaticResource
object(s):Or you could bind the
Background
property to theColor
object using aConverter
of some kind: