【问题标题】:WPF Style Trigger Sets Button Foreground on IsPressed, but not BackgroundWPF 样式触发器在 IsPressed 上设置按钮前景,而不是背景
【发布时间】:2017-03-27 16:02:28
【问题描述】:

我有以下 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>

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

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    有可能在按钮的模板(ControlTemplate)中,一些触发器将背景更改为不同的颜色。就“强度”而言,它比风格的触发器更强,这就是它生效的原因。尝试以您发布的“ButtonStyle”样式编辑按钮模板并将触发器放在那里。

    【讨论】:

    • 会的。任何有关此文档的链接?我想我可以直接转储按钮的模板并直接阅读它,但是有本书很好。
    【解决方案2】:

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

    【讨论】:

    • 谢谢,这个链接很有帮助。我所追求的是一种简单的方法,可以让 WPF 按钮在鼠标悬停并按下时改变外观。我有点惊讶它几乎没有变化,当我用鼠标指针按下它们时,我见过的大多数 Windows 按钮似乎实际上都在移动。关于如何在 WPF 中轻松实现这一点的任何建议?再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多