WPF, XAML: How to style a ListBoxItem using binding on property of ListBox ItemsSource object? WPF, XAML: How to style a ListBoxItem using binding on property of ListBox ItemsSource object? wpf wpf

WPF, XAML: How to style a ListBoxItem using binding on property of ListBox ItemsSource object?


Use ItemContainerStyle:

<ListBox ItemsSource="{Binding LogMessages}">    <ListBox.ItemContainerStyle>        <Style TargetType="ListBoxItem">            <Setter Property="Background" Value="{Binding Severity, Converter={StaticResource YourBackgroundConverter}}"/>        </Style>    </ListBox.ItemContainerStyle></ListBox>


Like Bojan commented, it's the RelativeSource which shouldnt be there.Use {Binding Path=Severity, Converter={StaticResource BackgroundSeverityConverter}} when you're binding to your data object. RelativeSource.TemplatedParent is for binding to ListBoxItem.

Additionally, something of a pet peeve of mine, you could consider using triggers, for example:

<Style x:Key="BindingAlternation" TargetType="{x:Type ListBoxItem}">    <Style.Triggers>        <DataTrigger Binding="{Binding Severity}" Value="1">            <Setter Property="Background" Value="Green"/>        </DataTrigger>        <DataTrigger Binding="{Binding Severity}" Value="2">            <Setter Property="Background" Value="Yellow"/>        </DataTrigger>        <!-- etc.. -->    </Style.Triggers><Style x:Key="BindingAlternation" TargetType="{x:Type ListBoxItem}">

But that's just a personal preference....what you have there should work fine if you fix the binding.