wpf 如何在 XAML 中为边框设置 MouseOver 事件/触发器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2388429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:32:32  来源:igfitidea点击:

How to set MouseOver event/trigger for border in XAML?

wpfxamltriggers

提问by Boris

I want the border to turn green when the mouse is over it and then to return to blue when the mouse is no longer over the border.

我希望边框在鼠标悬停在边框上方时变为绿色,然后在鼠标不再悬停在边框上方时返回蓝色。

I attempted this without any luck:

我在没有任何运气的情况下尝试了这个:

<Border 
    Name="ClearButtonBorder" 
    Grid.Column="1" 
    CornerRadius="0,3,3,0" 
    Background="Blue">
    <Border.Triggers>
        <Trigger Property="Border.IsMouseOver" Value="True">
            <Setter Property="Border.Background" Value="Green" />
        </Trigger>
        <Trigger Property="Border.IsMouseOver" Value="False">
            <Setter Property="Border.Background" Value="Blue" />
        </Trigger>
    </Border.Triggers>
    <TextBlock 
        HorizontalAlignment="Center" 
        VerticalAlignment="Center" 
        Text="X" />
</Border>

How can one set a trigger or events for MouseOver?

如何为 MouseOver 设置触发器或事件?

回答by Grokys

Yes, this is confusing...

是的,这令人困惑......

According to this blog post, it looks like this is an omission from WPF.

根据这篇博客文章,看起来这是 WPF 的一个遗漏。

To make it work you need to use a style:

要使其工作,您需要使用一种样式:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

我想这个问题并不常见,因为大多数人倾向于将这类东西分解为一种样式,因此它可以用于多个控件。