You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在另一Style的Resources中定义的Button鼠标悬停样式不生效?

问题分析与解决

问题根源

你代码里的鼠标悬停触发器写在了Style.Resources内部的独立Button Style中,这个内部Style仅会应用到当前Button的子Button元素上(而你的Button没有子Button),所以Background和Foreground的修改完全不会生效。

而Border的CornerRadius能生效,是因为WPF默认Button模板里包含一个Border控件,这个Border会自动继承你在Style.Resources中定义的Border样式。

修复后的代码

修改ButtonStyle.xaml,把触发器直接放到主Style中,移除嵌套的内部Button Style:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button" x:Key="RoundedCorners">
        <!-- 直接在这里定义触发器 -->
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Red"/>
                <Setter Property="Foreground" Value="Green"/>
            </Trigger>
        </Style.Triggers>
        <Style.Resources>
            <Style TargetType="Border">
                <Setter Property="CornerRadius" Value="5"/>
            </Style>
        </Style.Resources>
    </Style>
</ResourceDictionary>

补充说明

如果需要给Button的默认模板元素设置样式,Style.Resources是合适的位置(比如你设置Border的CornerRadius),但针对Button自身的属性修改和触发器,必须直接定义在目标Button的Style层级下,不能嵌套到内部的子Style中。

内容的提问来源于stack exchange,提问作者Ednik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:40:45