.NET 8 MAUI按钮点击动画失效问题咨询
.NET 8 MAUI按钮点击淡入淡出动画失效问题解决
问题原因
.NET 8 MAUI对控件默认视觉样式与状态管理做了轻量化优化,默认按钮的Pressed状态淡入淡出动画被从原生默认样式中移除,以此为开发者提供更灵活的自定义空间。
恢复动画的方法
1. 为单个按钮添加自定义视觉状态动画
直接在XAML中为目标按钮配置视觉状态,定义按压与释放时的透明度动画:
<Button Text="点击测试"> <VisualStateManager.VisualStateGroups> <VisualStateGroup Name="CommonStates"> <VisualState Name="Normal" /> <VisualState Name="Pressed"> <VisualState.Storyboard> <DoubleAnimation Duration="0:0:0.1" To="0.7" Storyboard.TargetProperty="Opacity" /> </VisualState.Storyboard> </VisualState> <VisualState Name="Released"> <VisualState.Storyboard> <DoubleAnimation Duration="0:0:0.1" To="1" Storyboard.TargetProperty="Opacity" /> </VisualState.Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Button>
2. 创建全局按钮样式(应用到所有按钮)
在Resources/Styles/Styles.xaml中定义全局按钮样式,替换默认样式实现全局生效:
<Style TargetType="Button" BasedOn="{StaticResource BaseStyle}"> <Setter Property="VisualStateManager.VisualStateGroups"> <VisualStateGroupList> <VisualStateGroup Name="CommonStates"> <VisualState Name="Normal" /> <VisualState Name="Pressed"> <VisualState.Storyboard> <DoubleAnimation Duration="0:0:0.1" To="0.7" Storyboard.TargetProperty="Opacity" /> </VisualState.Storyboard> </VisualState> <VisualState Name="Released"> <VisualState.Storyboard> <DoubleAnimation Duration="0:0:0.1" To="1" Storyboard.TargetProperty="Opacity" /> </VisualState.Storyboard> </VisualState> </VisualStateGroup> </VisualStateGroupList> </Setter> </Style>
3. 通过Handler实现平台级原生动画
如果需要更贴近原生平台的动画表现,可针对不同平台自定义按钮Handler:
以Android平台为例,在Platforms/Android/Handlers/CustomButtonHandler.cs中编写逻辑:
using Android.Views; using Microsoft.Maui.Handlers; namespace YourAppNamespace.Platforms.Android.Handlers; public class CustomButtonHandler : ButtonHandler { protected override void ConnectHandler(View platformView) { base.ConnectHandler(platformView); platformView.Touch += OnTouch; } protected override void DisconnectHandler(View platformView) { platformView.Touch -= OnTouch; base.DisconnectHandler(platformView); } private void OnTouch(object sender, View.TouchEventArgs e) { var nativeButton = sender as Android.Widget.Button; if (e.Event.Action == MotionEventActions.Down) { nativeButton.Animate().Alpha(0.7f).SetDuration(100).Start(); } else if (e.Event.Action is MotionEventActions.Up or MotionEventActions.Cancel) { nativeButton.Animate().Alpha(1f).SetDuration(100).Start(); } } }
随后在MauiProgram.cs中注册该Handler:
builder.ConfigureMauiHandlers(handlers => { #if ANDROID handlers.AddHandler(typeof(Button), typeof(CustomButtonHandler)); #endif });
内容的提问来源于stack exchange,提问作者Christopher Townsend
相关产品推荐
相关产品推荐

