ListBox ItemContainerStyle and ItemTemplate interaction

2.1k Views Asked by At

I have a list box with a displaying a list of checkbox, and I would like to change the foreground of the checkbox depending on whether the item in the list box is selected or not (not whether the checkbox is selected). The behaviour of the control is fine if the ItemTemplate is a simple TextBlock, however the foreground doesn't change if the ItemTemplate is checkbox.
Could someone explain to me why it doesn't work for a checkbox?

With TextBox:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Foreground" Value="Black" />
        <Style.Triggers>
            <Trigger Property="ListBoxItem.IsSelected" Value="True">
                <Trigger.Setters>
                    <Setter Property="Foreground" Value="White" />
                </Trigger.Setters>
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Path=TextToDisplay}"  />
    </DataTemplate>
</ListBox.ItemTemplate>

With CheckBox:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Foreground" Value="Black" />
        <Style.Triggers>
            <Trigger Property="ListBoxItem.IsSelected" Value="True">
                <Trigger.Setters>
                    <Setter Property="Foreground" Value="White" />
                </Trigger.Setters>
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox Content="{Binding Path=TextToDisplay}"  />
    </DataTemplate>
</ListBox.ItemTemplate>
1

There are 1 best solutions below

0
On

You can use Foreground binding

    <CheckBox 
        Content="{Binding Path=TextToDisplay}" 
        Foreground="{Binding Path=Foreground, 
        RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" 
    />