简体   繁体   中英

Application MainWindow is null in WPF (using Caliburn Micro)

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?

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;
}

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.

eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM