我是 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();
在OnStartUp方法中App.xaml.cs,因為它需要一個引數。
打開窗戶的最佳方法是什么?
我嘗試使用StartupUri="MainView.xaml"in App.xaml,但我需要OnStartup配置服務等的方法。
uj5u.com熱心網友回復:
我猜你應該再次嘗試理解依賴注入。此外,在使用 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();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/330481.html
下一篇:ListView項未正確顯示
