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

WPF鼠标悬停时修改Button的FontWeight及FontStyle失效问题咨询

问题原因

你的字体属性不生效是两个配置缺失导致的:

  1. Button 本身原生自带 FontWeight、FontStyle 依赖属性,你使用 TextBlock.FontWeight 这种附加属性写法时,属性变更不会自动传递给 ControlTemplate 内的内容承载控件。
  2. 你自定义模板里的 ContentPresenter 没有绑定模板父级的字体相关属性,即使 Button 本身的字体属性变更,内部显示的内容也无法同步生效。

调整方案

你只需要修改三处配置即可,修改后的完整样式代码如下:

<Window.Resources>
    <Style TargetType="Button" x:Key="mouseOverStyle">
        <!-- 1. 去掉TextBlock前缀,直接用Button自带的字体属性 -->
        <Setter Property="Foreground" Value="#FF808080" />
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="FontWeight" Value="Normal" />
        <Setter Property="FontStyle" Value="Normal" />
        <!-- 按需设置默认边框样式,悬停时修改边框的话可以直接在Trigger里加对应Setter -->
        <Setter Property="BorderBrush" Value="Transparent" />
        <Setter Property="BorderThickness" Value="2" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button" >
                    <Border x:Name="Border" 
                            Background="{TemplateBinding Background}"  
                            BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="{TemplateBinding BorderThickness}" >
                        <!-- 2. 给ContentPresenter添加字体属性的模板绑定,同步父级Button的属性变化 -->
                        <ContentPresenter HorizontalAlignment="Center" 
                                          VerticalAlignment="Center"
                                          FontWeight="{TemplateBinding FontWeight}"
                                          FontStyle="{TemplateBinding FontStyle}"
                                          Foreground="{TemplateBinding Foreground}"/>
                    </Border>
                    <ControlTemplate.Triggers >
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="White" />
                            <Setter Property="Background" Value="#FF303030" />
                            <!-- 3. 去掉TextBlock前缀,直接设置Button自带的字体属性 -->
                            <Setter Property="FontWeight" Value="Bold" />
                            <Setter Property="FontStyle" Value="Italic" />
                            <!-- 如果需要悬停修改边框,直接加这行即可,Value替换为你需要的边框色 -->
                            <Setter Property="BorderBrush" Value="#FF0078D7" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

修改完成后直接给Button应用mouseOverStyle即可,悬停时所有属性都会正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:24:04