Avalonia 通过异步加载解决加载卡顿

Avalonia 通过异步加载解决加载卡顿

如果我们进行页面切换,特别是在面对一些大型场景,其实可能会感到 Avalonia 的卡顿,这个时候你可以试试使用基于 Load 和 IsVisible 的延迟加载。

一、代码

    public class AsyncLoadHelper
    {
        public static readonly AttachedProperty<bool> IsAsyncProperty = AvaloniaProperty.RegisterAttached<AsyncLoadHelper, Control, bool>("IsAsync", false, coerce: (a, b) =>
        {
            if(a is Control c)
            {
                c.IsVisible = false;
                c.Loaded += C_Loaded;
            }
            return true;
        });

        private static void C_Loaded(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
        {
            if (sender is Control c)
            {
                c.Loaded -= C_Loaded;
                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    c.IsVisible = true;
                });
            }
        }

        public static bool GetIsAsync(Control element) => (bool)element.GetValue(IsAsyncProperty);
        public static void SetIsAsync(Control element, bool value) => element.SetValue(IsAsyncProperty, value);
    }

二、使用方式

    <Panel helper:AsyncLoadHelper.IsAsync="True">
        <!--  TODO  -->
    </Panel>
posted @ 2025-06-16 10:06  fanbal  阅读(149)  评论(0)    收藏  举报