Xamarin.Forms转MAUI后Expander动画属性报错及替代方案咨询
问题解决与替代方案
原因说明
MAUI Community Toolkit中的Expander控件移除了Xamarin.Forms版本里的CollapseAnimationLength和ExpandAnimationLength属性,改用统一的AnimationDuration属性控制展开/收起的动画时长,直接沿用原属性会导致报错。
替代实现方案
1. 使用统一的AnimationDuration属性
如果展开和收起动画时长可以设置为相同值,直接替换为AnimationDuration即可,同时要更新MAUI Toolkit的命名空间:
xmlns:xct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" <xct:Expander x:Name="Fab" Margin="12" AnimationDuration="100" />
2. 自定义Expander实现差异化动画时长
如果需要展开和收起时长不同,可通过自定义Expander类实现:
- 创建自定义Expander,继承自MAUI Community Toolkit的Expander
- 添加
CollapseAnimationDuration和ExpandAnimationDuration绑定属性 - 重写展开/收起的动画逻辑,使用自定义属性控制时长
示例后台代码:
using CommunityToolkit.Maui.Views; public class CustomExpander : Expander { public static readonly BindableProperty ExpandAnimationDurationProperty = BindableProperty.Create(nameof(ExpandAnimationDuration), typeof(uint), typeof(CustomExpander), 250u); public static readonly BindableProperty CollapseAnimationDurationProperty = BindableProperty.Create(nameof(CollapseAnimationDuration), typeof(uint), typeof(CustomExpander), 250u); public uint ExpandAnimationDuration { get => (uint)GetValue(ExpandAnimationDurationProperty); set => SetValue(ExpandAnimationDurationProperty, value); } public uint CollapseAnimationDuration { get => (uint)GetValue(CollapseAnimationDurationProperty); set => SetValue(CollapseAnimationDurationProperty, value); } protected override async Task OnExpandedChangedAsync(bool expanded, CancellationToken token) { if (Content == null) { await base.OnExpandedChangedAsync(expanded, token); return; } Content.IsVisible = true; var duration = expanded ? ExpandAnimationDuration : CollapseAnimationDuration; if (expanded) { await Content.FadeTo(1, duration, Easing.CubicInOut); await Content.ScaleTo(1, duration, Easing.CubicInOut); } else { await Content.FadeTo(0, duration, Easing.CubicInOut); await Content.ScaleTo(0.9, duration, Easing.CubicInOut); Content.IsVisible = false; } await base.OnExpandedChangedAsync(expanded, token); } }
XAML中使用自定义控件(需添加自定义命名空间):
xmlns:local="clr-namespace:你的项目命名空间" <local:CustomExpander x:Name="Fab" Margin="12" ExpandAnimationDuration="100" CollapseAnimationDuration="0" />
额外注意事项
- 确保安装最新版本的
CommunityToolkit.MauiNuGet包,避免版本兼容问题 - 必须替换原Xamarin Toolkit的命名空间为MAUI版本的
http://schemas.microsoft.com/dotnet/2022/maui/toolkit
内容的提问来源于stack exchange,提问作者Surendhar
相关产品推荐
相关产品推荐

