MainWindow application is null in WPF (using Caliburn Micro)

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

Application.Current.MainWindow null

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

+6
source share
2 answers

This is ridiculous, I just answered it 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; } 
+13
source

1. Understanding Application.Current.MainWindow

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

eg. if you open LoginWindow at startup, then Application.Current.MainWindow will be LoginWindow . When you close LoginWindow , then Application.Current.MainWindow could be Window1 , for example.

2. Access to an instance of MainWindow

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

however, if MainWindow does not open, it returns null. Do not try to get around this - if MainWindow is not already open or it is already closed, you should not access it.

3. MVVM

in the MVVM template, you should not access views directly from your view modes. If you did, you would break basic MVVM issues, such as separation of concerns, testability, etc. Etc. The question is why you want mvvm.

If you want to perform an action in MainWindow , you must perform the action on MainWindowViewModel . If the window is open, it will reflect the changes in the ViewModel. If this is not the case, then the change should not be reflected. MainWindowViewModel should not have a direct link to an instance of MainWindow .

+3
source

Source: https://habr.com/ru/post/953330/


All Articles