[英]What's the difference between ItemTemplate and ItemContainerStyle in a WPF ListBox?
[英]ListBox ItemContainerStyle and ItemTemplate interaction
我有一个带有显示复选框列表的列表框,并且我想根据是否选中列表框中的项目(而不是选中复选框)来更改复选框的前景。 如果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>
使用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>
您可以使用Foreground
绑定
<CheckBox
Content="{Binding Path=TextToDisplay}"
Foreground="{Binding Path=Foreground,
RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.