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 .
Liero source share