Maui添加启动页

Maui添加启动页

  1. 普通Page模式
    App.xaml.cs的构造函数中替换MainPage的对象。

    1
    2
    3
    4
    5
    6
    
    public App()
    {
        InitializeComponent();
    
        MainPage = new NewPage1();
    }
    
  2. MVVM模式
    App.xaml.cs中重写CreateWindow方法。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
    protected override Window CreateWindow(IActivationState? activationState)
    {
        NewPage1? desktopShellService = Handler.MauiContext!.Services.GetService<NewPage1>();
        Window window = new Window(desktopShellService)
        {
            Width = DeviceDisplay.Current.MainDisplayInfo.Width / 2,
            Height = DeviceDisplay.Current.MainDisplayInfo.Height / 2,
        };
        return window;
    }
    
  3. 启动页切换到主页面
    在页面的Loaded事件或其他事件中加入MainPage对象切换。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    async Task Loaded()
    {
        await Task.Delay(5000);
        _ = Task.Run(() =>
        {
            AppShell? desktopShellService = Application.Current.Handler.MauiContext!.Services.GetService<AppShell>();
            if (desktopShellService != null && desktopShellService != Application.Current.MainPage)
            {
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    Application.Current.MainPage = desktopShellService;
                });
            }
        });
        //AppShell? desktopShellService = Application.Current.Handler.MauiContext!.Services.GetService<AppShell>();
        //if (desktopShellService != null && desktopShellService != Application.Current.MainPage)
        //{
        //    Application.Current.MainPage = desktopShellService;
        //}
    }
    
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy