[英]Application MainWindow is null in WPF (using Caliburn Micro)
我正在開發WPF應用程序,我需要指向控件內應用程序的主窗口。 我正在使用Caliburn Micro。
Application.Current.MainWindow
為null
如何在Caliburn Micro中獲得對應用程序MainWindow
的引用?
很好笑,我剛剛在另一篇文章中對此進行了回答...嘗試在MainWindow.xaml.cs
文件的Loaded
事件中設置Application.Current.MainWindow
屬性:
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Application.Current.MainWindow = this;
}
1.了解Application.Current.MainWindow
當您的應用程序打開第一個窗口( MainWindow.xaml
)時,該窗口將設置為Application.Current.MainWindow
。 關閉窗口后,另一個當前打開的窗口將設置為Application.Current.MainWindow
。 如果沒有打開的窗口,則將Application.Current.MainWindow設置為null。
例如,如果在啟動時打開LoginWindow
,則Application.Current.MainWindow
將為LoginWindow
。 當您關閉LoginWindow
, Application.Current.MainWindow
可以是例如Window1
。
2.訪問MainWindow實例
如果要訪問MainWindow類的實例,則應執行以下操作: Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
但是,如果未打開MainWindow,則它將返回null。 不要嘗試解決此問題-如果MainWindow尚未打開,或者已經關閉,則不應訪問它。
3. MVVM
在MVVM模式中,您不應直接從視圖模型訪問視圖。 如果這樣做了,您將打破主要的MVVM問題,例如關注點分離,可測試性等。然后的問題是,為什么要使用mvvm。
如果你想在執行某些操作MainWindow
,你應該執行動作MainWindowViewModel
。 如果打開窗口,它將反映ViewModel中的更改。 如果不是,則不必反映所做的更改。 MainWindowViewModel
不應直接引用MainWindow
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.