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.