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

WinUI 3圆形按钮如何恢复鼠标悬停动画效果?

恢复WinUI 3圆形按钮的鼠标悬停动画

你的问题出在自定义ControlTemplate未添加视觉状态管理,普通按钮的悬停效果依赖VisualStateManager响应鼠标状态变化,而你当前的模板仅固定了Ellipse的填充色,因此无法触发动态样式变化。

解决方法是在模板中加入VisualStateManager,定义PointerOver(鼠标悬停)状态下的样式变化,还可添加过渡动画让效果更流畅。以下是修改后的完整代码:

<Button Width="80" Height="80">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Grid>
                <Ellipse x:Name="ButtonEllipse" Fill="Green" />
                <FontIcon FontSize="16" Glyph="&#xE8E5;" />
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                
                <!-- 视觉状态管理模块 -->
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CommonStates">
                        <!-- 默认状态 -->
                        <VisualState x:Name="Normal" />
                        
                        <!-- 鼠标悬停状态:实现填充色平滑过渡 -->
                        <VisualState x:Name="PointerOver">
                            <Storyboard>
                                <ColorAnimation 
                                    Storyboard.TargetName="ButtonEllipse"
                                    Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
                                    To="DarkGreen"
                                    Duration="0:0:0.2" />
                            </Storyboard>
                        </VisualState>
                        
                        <!-- 可选:添加按钮按下状态的样式 -->
                        <VisualState x:Name="Pressed">
                            <Storyboard>
                                <ColorAnimation 
                                    Storyboard.TargetName="ButtonEllipse"
                                    Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
                                    To="ForestGreen"
                                    Duration="0:0:0.1" />
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

关键说明:

  • 给Ellipse命名ButtonEllipse,方便动画定位目标元素
  • CommonStates是WinUI控件默认状态组,包含Normal、PointerOver、Pressed等常用交互状态
  • ColorAnimation实现填充色的平滑过渡,可根据需求修改To的颜色值和Duration动画时长
  • 若想和系统默认按钮风格统一,可将固定颜色替换为主题资源,比如把Fill="Green"改成Fill="{ThemeResource ButtonBackground}",悬停时的To值用{ThemeResource ButtonBackgroundPointerOver}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:05:05