且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF:ListBoxItem.IsSelected 的触发器不适用于 Background 属性

更新时间:2022-03-18 03:24:56

稍微反思一下 Aero 风格就可以解释为什么这个简单的触发器设置不起作用.

A little bit of reflecting on the Aero-style offers us an explanation to why this simple trigger-setting doesn't work.

ListBoxItem 有一个 ControlTemplate,其中的触发器优先于我们的触发器.至少这对于 MultiTrigger 来说似乎是正确的.我已经设法覆盖 Selected=true 的简单触发器,但对于多重触发器,我必须制作自己的 ControlTemplate.

The ListBoxItem has a ControlTemplate with triggers that takes precedence over our trigger. At least this seems to be true for a MultiTrigger. I´ve managed to override the simple trigger of Selected=true but for the multitrigger I had to make my own ControlTemplate.

这是显示有问题的 MultiTrigger 的 Aero 样式的模板:

This is the template from the Aero style that shows the problematic MultiTrigger:

<ControlTemplate TargetType="{x:Type ListBoxItem}">
    <ControlTemplate.Triggers>
        <Trigger Property="IsSelected" Value="true">
            <Setter TargetName="Bd" Value="{DynamicResource {x:Static HighlightBrush}}" Property="Background" />
            <Setter Value="{DynamicResource {x:Static HighlightTextBrush}}" Property="Foreground" />
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="true" />
                <Condition Property="IsSelectionActive" Value="false" />
            </MultiTrigger.Conditions>
            <Setter TargetName="Bd" Value="{DynamicResource {x:Static ControlBrush}}" Property="Background" />
            <Setter Value="{DynamicResource {x:Static ControlTextBrush}}" Property="Foreground" />
        </MultiTrigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Value="{DynamicResource {x:Static GrayTextBrush}}" Property="Foreground" />
        </Trigger>
    </ControlTemplate.Triggers>
    <Border Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
    </Border>
</ControlTemplate>

希望它能把事情弄清楚一点.我无法理解他们为什么将风格如此复杂化.

Hope it clears things up a little bit. I can't fathom why they´ve overcomplicated the style this much.