如何在 WPF 中更改 Button MouseOver 的背景? [英] How do you change Background for a Button MouseOver in WPF?

查看:37
本文介绍了如何在 WPF 中更改 Button MouseOver 的背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一个带有此 XAML 的按钮:

I have a button on my page with this XAML:

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" 
    Width="50" Height="50" HorizontalContentAlignment="Left" 
    BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Background" Value="Green"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

但是当我将鼠标放在按钮上时,按钮的背景会更改为默认的 Windows 灰色背景.
有什么问题?

But when I put mouse over my button, button's background changes to default windows gray background.
What's The Problem?

这是鼠标悬停前后的按钮图片:
之前:

之后:

This is the button picture before and after mouseover:
Before:

After:

推荐答案

要删除 Button 上的默认 MouseOver 行为,您需要修改 ControlTemplate.将您的 Style 定义更改为以下内容应该可以解决问题:

To remove the default MouseOver behaviour on the Button you will need to modify the ControlTemplate. Changing your Style definition to the following should do the trick:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Green"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

已经晚了几年,但您实际上可以在那里的边框内设置边框画笔.Idk 如果有人指出,但似乎不是......

It's a few years late, but you are actually able to set the border brush inside of the border that is in there. Idk if that was pointed out but it doesn't seem like it was...

这篇关于如何在 WPF 中更改 Button MouseOver 的背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆