简体   繁体   English

在 WPF MVVM 中打开主窗口

[英]Open Main Window in WPF MVVM

I am new to WPF and am building a WPF MVVM application.我是 WPF 的新手,正在构建 WPF MVVM 应用程序。

I can't seem to figure out how to open the main window in my app.我似乎无法弄清楚如何在我的应用程序中打开主窗口。

App.xaml应用程序.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应用程序.xaml.cs

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

    //configure host

    await _host.StartAsync();
}

I need to add MainView as the main window.我需要添加MainView作为主窗口。

MainView.xaml.cs主视图.xaml.cs

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

Since I have a parameterized constructor, injecting the ViewModel (via dependency injection) and setting the DataContext to it, I can't simply add由于我有一个参数化的构造函数,注入 ViewModel(通过依赖注入)并将DataContext设置为它,我不能简单地添加

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

in the OnStartUp method in App.xaml.cs , as it needs a parameter.App.xaml.csOnStartUp方法中,因为它需要一个参数。

What is the best approach to open the window?打开窗户的最佳方法是什么?

I have tried using StartupUri="MainView.xaml" in App.xaml , but I need the OnStartup method to configure the services and so on.我曾尝试在App.xaml使用StartupUri="MainView.xaml" ,但我需要OnStartup方法来配置服务等等。

You should try again to understand dependency injection I guess.我猜你应该再次尝试理解依赖注入。 Also when using an IoC container you also want to apply the Dependency Inversion principle.此外,在使用 IoC 容器时,您还需要应用依赖倒置原则。 Otherwise dependency injection is very useless and only overcomplicates your code.否则依赖注入是非常无用的,只会使您的代码过于复杂。

You must retrieve the composed instance from the IoC container.您必须从 IoC 容器中检索组合实例。 In your case, it seems you are using the .NET Core dependency injection framework.在您的情况下,您似乎正在使用 .NET Core 依赖项注入框架。 In general, the pattern is the same for every IoC framework: 1) register dependencies 2) compose the dependency graph 3) get the startup view from the container and show it 4) dispose the container (handle lifecycle - don't pass it around!):一般来说,每个 IoC 框架的模式都是相同的:1) 注册依赖项 2) 组合依赖关系图 3) 从容器中获取启动视图并显示它 4) 处置容器(处理生命周期 - 不要传递它!):

App.xaml.cs应用程序.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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM