1

我有一个显示复选框列表的列表框,我想根据列表框中的项目是否被选中(而不是复选框是否被选中)来更改复选框的前景。如果 ItemTemplate 是一个简单的 TextBlock,则控件的行为很好,但是如果 ItemTemplate 是复选框,则前景不会改变。
有人可以向我解释为什么它不适用于复选框吗?

使用文本框:

<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>

使用复选框:

<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>
4

1 回答 1

0

您可以使用Foreground绑定

    <CheckBox 
        Content="{Binding Path=TextToDisplay}" 
        Foreground="{Binding Path=Foreground, 
        RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" 
    />
于 2014-07-29T03:20:00.060 回答