WPF 样式触发器在按下时设置按钮前景,但不设置背景



我有以下 XAML 代码,它创建一个带有单个按钮的窗口。当我单击按钮时,前景色变为红色,但背景色没有变化。为什么一个会改变,而另一个不会改变?

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfExperiments"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid Margin="0,0,0,2">
        <Grid.Resources>
            <Style x:Key="ButtonStyle" TargetType="Button">
                <Style.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Foreground" Value="Red"/>
                        <Setter Property="Background" Value="Red"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <Button Style="{StaticResource ButtonStyle}" 
                Content="Button"
                HorizontalAlignment="Left"
                Margin="135,97,0,0"
                VerticalAlignment="Top"
                Width="75"
                />
    </Grid>
</Window>

当然,我先用谷歌搜索过这个。我发现的大多数内容都说解决方法是使用模板而不是样式,如果这是解决方案,我当然愿意这样做。但我在一个 SO 答案中注意到按钮具有覆盖样式值的默认模板。如果是这样,为什么我的 XAML 会影响前台?

前台

不受影响,因为按下按钮时按钮的默认模板不会更新前景。 它只更新背景。
默认模板的触发器在样式的触发器之后执行,这就是您的背景不受样式影响的原因。
更多
解释在这里 http://harishasanblog.blogspot.com/2011/02/ismouseover-trigger-not-working-in-wpf.html

按钮的模板(控件模板(中,某些触发器可能会将背景更改为不同的颜色。从"强度"来看,它比样式的扳机更强,这就是它生效的原因。尝试以您发布的"按钮样式"样式编辑按钮的模板,并将触发器放在那里。

最新更新