如何在.NET MAUI中实现底部滑窗的平滑移动?
解决.NET MAUI BottomSheet平滑动画失效问题
问题排查点及解决方案
1. 控件高度未正确获取,导致动画位移异常
直接在点击事件中取ContextDescription.Height时,控件可能还未完成布局,高度值不准确(比如为0),导致maxTranslation计算错误,动画实际位移过小,看起来生硬。
修复方式:
通过SizeChanged事件缓存控件实际高度:
private double _cachedContentHeight; // 在页面构造函数中绑定事件 public YourPage() { InitializeComponent(); ContextDescription.SizeChanged += OnContentSizeChanged; } private void OnContentSizeChanged(object sender, EventArgs e) { if (ContextDescription.Height > 0) _cachedContentHeight = ContextDescription.Height; }
在MoveBottomSheet中替换为缓存高度:
double maxContentHeight = _cachedContentHeight;
2. TranslateTo的Easing参数未生效,手动创建动画替代
MAUI的TranslateTo快捷方法在部分场景下无法正确应用Easing,改用Animation类手动创建动画,确保缓动效果生效:
private void MoveBottomSheet(bool close) { double initialTranslation = DeviceInfo.Idiom == DeviceIdiom.Phone ? -5.0 : -15.0; double maxTranslation = _cachedContentHeight + 20.0; double finalTranslation; if (_isInitialOpen) { finalTranslation = initialTranslation; _isInitialOpen = false; } else { finalTranslation = close ? initialTranslation : -maxTranslation; } // 手动创建动画并应用Easing var slideAnimation = new Animation( callback: value => BottomSheet.TranslationY = value, start: BottomSheet.TranslationY, end: finalTranslation, easing: Easing.SinIn ); slideAnimation.Commit( owner: BottomSheet, name: "BottomSheetSlide", length: 450, finished: (completed, canceled) => Debug.WriteLine($"动画完成:{completed}") ); }
3. 初始位置设置时机错误,确保布局完成后赋值
第一次设置初始位置时,若控件未完成布局,会导致动画起始点异常。在OnAppearing中延迟设置初始位置:
protected override async void OnAppearing() { base.OnAppearing(); await Task.Delay(100); // 等待布局完成 _isInitialOpen = true; BottomSheet.TranslationY = DeviceInfo.Idiom == DeviceIdiom.Phone ? -5.0 : -15.0; _isInitialOpen = false; }
4. 检查布局容器约束
确保BottomSheet放在合适的布局容器中,比如AbsoluteLayout并锚定在底部,或Grid中设置VerticalOptions="End",保证TranslationY的变化对应上下滑动的视觉效果,避免布局约束抵消动画效果。
内容的提问来源于stack exchange,提问作者bluedra
相关产品推荐
相关产品推荐

