如何在 .NET MAUI Shell 中正确使用 MVVM 模式

本教程介绍了在 .NET MAUI Shell 应用中,如何通过依赖注入和服务注册(AddSingleton)来正确地集成和使用 MVVM 模式。

  1. 注册服务

    1
    
    services.AddSingleton<AppShell, ShellViewModel>();
    
  2. 修改App.xaml.cs

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    public App()
    {
        InitializeComponent();
    
        MauiExceptions.UnhandledException += (sender, args) =>
        {
            Exception? exception = args.ExceptionObject as Exception;
        };
    }
    protected override Window CreateWindow(IActivationState? activationState)
    {
        AppShell? appShell = activationState?.Context.Services.GetService<AppShell>();
        Window window = new(appShell!);
        return window;
    }
    
Built with Hugo
Theme Stack designed by Jimmy