在 WPF MVVM 中打开 Main Window

Open Main Window in WPF MVVM

我是 WPF 新手,正在构建 WPF MVVM 应用程序。

我似乎不知道如何在我的应用程序中打开主 window。

App.xaml

<Application
    x:Class="First.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DispatcherUnhandledException="OnDispatcherUnhandledException"
    Startup="OnStartup" />

App.xaml.cs

private async void OnStartup(object sender, StartupEventArgs e)
{
    var appLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

    //configure host

    await _host.StartAsync();
}

我需要添加 MainView 作为主要 window。

MainView.xaml.cs

public MainView(MainViewModel viewModel)
{
    InitializeComponent();
    DataContext = viewModel;
}

因为我有一个参数化的构造函数,注入 ViewModel(通过依赖注入)并设置 DataContext 给它,我不能简单地添加

MainView mainView = new MainView();
MainView.Show();

App.xaml.cs中的OnStartUp方法中,因为它需要一个参数。

打开 window 的最佳方法是什么?

我试过在App.xaml中使用StartupUri="MainView.xaml",但我需要OnStartup方法来配置服务等等。

我猜你应该再试一次来理解依赖注入。此外,在使用 IoC 容器时,您还需要应用 Dependency Inversion 原则。否则依赖注入是非常无用的,只会使你的代码过于复杂。

您必须从 IoC 容器中检索组合实例。在您的情况下,您似乎正在使用 .NET Core 依赖注入框架。通常,每个 IoC 框架的模式都是相同的:1) 注册依赖关系 2) 组成依赖关系图 3) 从容器获取启动视图并显示它 4) 处置容器(处理生命周期 - 不要传递它) !):

App.xaml.cs

private async void OnStartup(object sender, StartupEventArgs e)
{
  var services = new ServiceCollection();
  services.AddSingleton<MainViewModel>();
  services.AddSingleton<MainView>();
  await using ServiceProvider container = services.BuildServiceProvider();

  // Let the container compose and export the MainView
  var mainWindow = container.GetService<MainView>();

  // Launch the main view
  mainWindow.Show();
}