Application MainWindow is null in WPF (using Caliburn Micro)

这一生的挚爱 提交于 2019-12-08 19:10:42

问题


I am developing a WPF application and I need to get a point to the main window of application inside a control. I am using Caliburn Micro.

Application.Current.MainWindow is null

How can I get a reference to the MainWindow of application in Caliburn Micro?


回答1:


That's funny, I've just answered this in another post... Try setting the Application.Current.MainWindow property in the Loaded event in the MainWindow.xaml.cs file:

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Application.Current.MainWindow = this;
}



回答2:


1. Understanding of Application.Current.MainWindow

When your application opens first window (MainWindow.xaml), then the window is set to Application.Current.MainWindow. When the window is closed, then another currently opened window is set to Application.Current.MainWindow. If the there are no opened windows, then Application.Current.MainWindow is set to null.

e.g. if you open LoginWindow at startup then Application.Current.MainWindow will be LoginWindow. When you close LoginWindow, then Application.Current.MainWindow can be Window1 for instance.

2. Accessing MainWindow instance

if you want to access instance of MainWindow class you should do following: Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();

however, if MainWindow is not opened, then it will return null. Don't try to workaround this - if MainWindow is not opened yet, or it is closed already, you should not access it.

3. MVVM

in MVVM pattern, you should not access views directly from your viewmodels. If you did, you would break the major MVVM concerns, like Separation of concerns, testability, etc, etc. The question is then, why you want mvvm.

If you want to perform some action in MainWindow, you should perform the action on MainWindowViewModel. If window is opened, it will reflect the changes in ViewModel. If it is not, then the changed does not have to be reflected. MainWindowViewModel should not have direct reference to the MainWindow instance.



来源:https://stackoverflow.com/questions/18660256/application-mainwindow-is-null-in-wpf-using-caliburn-micro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!