简体   繁体   English

ListBox ItemContainerStyle和ItemTemplate交互

[英]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. 如果ItemTemplate是简单的TextBlock,则控件的行为很好,但是如果ItemTemplate为复选框,则前景不会改变。
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: 使用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 您可以使用Foreground绑定

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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