Wpf – Change background/highlight-color of selected ListBox item based on data

data-bindingwpfxaml

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:

<Style TargetType="ListBoxItem">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background">
                <Setter.Value>
                    <SolidColorBrush Color="{Binding Color}" />
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

Note that for this binding to work, you must have a property called Color on the data item objects that are set as the ListBox.ItemsSource.

UPDATE >>>

Ok, so that was my bad... I forgot that SolidColorBrush is not a FrameworkElement and is Freezable, so they cannot be used in a Binding... you have a few options:

Either create your colour(s) as StaticResource object(s):

<Trigger Property="IsSelected" Value="True">
    <Setter Property="Background" Value="{StaticResource Color}" />
</Trigger>

Or you could bind the Background property to the Color object using a Converter of some kind:

<Style TargetType="ListBoxItem" Background="{Binding Color, Converter={StaticResource 
SomeColourConverter}}" />
Related Topic