[英]Open Main Window in WPF MVVM
我是 WPF 的新手,正在构建 WPF MVVM 应用程序。
我似乎无法弄清楚如何在我的应用程序中打开主窗口。
应用程序.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" />
应用程序.xaml.cs
private async void OnStartup(object sender, StartupEventArgs e)
{
var appLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
//configure host
await _host.StartAsync();
}
我需要添加MainView
作为主窗口。
主视图.xaml.cs
public MainView(MainViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
由于我有一个参数化的构造函数,注入 ViewModel(通过依赖注入)并将DataContext
设置为它,我不能简单地添加
MainView mainView = new MainView();
MainView.Show();
在App.xaml.cs
的OnStartUp
方法中,因为它需要一个参数。
打开窗户的最佳方法是什么?
我曾尝试在App.xaml
使用StartupUri="MainView.xaml"
,但我需要OnStartup
方法来配置服务等等。
我猜你应该再次尝试理解依赖注入。 此外,在使用 IoC 容器时,您还需要应用依赖倒置原则。 否则依赖注入是非常无用的,只会使您的代码过于复杂。
您必须从 IoC 容器中检索组合实例。 在您的情况下,您似乎正在使用 .NET Core 依赖项注入框架。 一般来说,每个 IoC 框架的模式都是相同的:1) 注册依赖项 2) 组合依赖关系图 3) 从容器中获取启动视图并显示它 4) 处置容器(处理生命周期 - 不要传递它!):
应用程序.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.