8

我正在开发一个 WPF 应用程序,我需要指向控件内的应用程序主窗口。我正在使用 Caliburn Micro。

Application.Current.MainWindownull

如何MainWindow在 Caliburn Micro 中获得对应用程序的参考?

4

2 回答 2

18

这很有趣,我刚刚在另一篇文章中回答了这个问题......尝试在文件中的事件中设置Application.Current.MainWindow属性:LoadedMainWindow.xaml.cs

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Application.Current.MainWindow = this;
}
于 2013-09-06T14:43:17.597 回答
5

一、Application.Current.MainWindow的理解

当您的应用程序打开第一个窗口 ( MainWindow.xaml) 时,该窗口设置为Application.Current.MainWindow。当窗口关闭时,另一个当前打开的窗口设置为Application.Current.MainWindow。如果没有打开的窗口,则 Application.Current.MainWindow 设置为 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.

如果要在 中执行某些操作MainWindow,则应在 中执行操作MainWindowViewModel。如果窗口打开,它将反映 ViewModel 中的更改。如果不是,则不必反映更改的内容。MainWindowViewModel不应直接引用该MainWindow实例。

于 2015-07-15T10:45:27.843 回答