WPF触发器无法按预期工作

时间:2013-07-20 05:11:42

标签: wpf button triggers styles ismouseover

我想要一个红色按钮,当鼠标悬停在它上面时会变黑。

    <Button Content="Hover me" Grid.Column="3" Grid.Row="3">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background" Value="Red"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Black"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

然而,我的问题是,当我将鼠标悬停在按钮上时,它会变成具有渐变灰色外观的默认Windows样式。

1 个答案:

答案 0 :(得分:15)

试试吧

<Window.Resources>
    <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Red"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <ContentPresenter x:Name="PART_Content"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          TextElement.Foreground="{TemplateBinding Foreground}"></ContentPresenter>                        </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Black"/>
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

并将自定义样式应用于以下

<Button Content="Hover me" Style="{StaticResource MyButtonStyle}" Height="30" Width="100"/>

原因是Button的默认Aero样式。它在ControlTemplate中定义了一个chrome,它在各种鼠标事件上都有自己的行为。那就过来写你的触发器调用了。

因此,您必须覆盖Button的默认ControlTemplate以获得所需的结果。