打开WPF MVVM的主窗口



我是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方法来配置服务等等。

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

必须从IoC容器中检索组合实例。在你的情况下,似乎你正在使用。net核心依赖注入框架。一般来说,每个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();
}

最新更新