【问题标题】:Open Main Window in WPF MVVM在 WPF MVVM 中打开主窗口
【发布时间】:2021-10-21 12:21:55
【问题描述】:

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

我似乎不知道如何在我的应用中打开主窗口。

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作为主窗口。

MainView.xaml.cs

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

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

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

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

打开窗口的最佳方法是什么?

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

【问题讨论】:

  • 为什么需要参数化构造函数? DataContext 是一个公共属性,可以在创建视图后随时设置。
  • @Clemens 我还能在哪里设置它?
  • 不知道。我们不知道 MainViewModel 实例是如何以及何时创建的。一旦有了视图模型实例,就将它分配给 MainView 的 DataContext。
  • 我想这会解决我的问题,谢谢!
  • @Clemens 问题是我没有在任何地方实例化 MainViewModel,我正在搜索我的代码中所有出现的 MainViewModel 并且只有一个 -services.AddSingleton&lt;MainViewModel&gt;();。另一个是MainView中DataContext的构造函数注入和设置。

标签: c# wpf mvvm view


【解决方案1】:

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

您必须从 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();
}

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多