简体   繁体   中英

ListBox ItemContainerStyle and ItemTemplate interaction

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>

You can use Foreground binding

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM