为何在另一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
相关产品推荐
相关产品推荐

