获取当前 MainWindow 实例的 WPF 最佳实践?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41333040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF best practice to get current MainWindow instance?
提问by ganjeii
I got a warning that this may be a subjective question and might be closed, but I'm going to ask anyway.
我收到警告说这可能是一个主观问题并且可能会被关闭,但我还是会问。
I'm basically trying to access a button on my MainWindow in a WPF application from a UserControl that gets loaded up from within the MainWindow.
我基本上是在尝试从从 MainWindow 中加载的 UserControl 访问 WPF 应用程序中 MainWindow 上的按钮。
I'm currently accessing it like this from the UserControl's code behind:
我目前正在从后面的 UserControl 代码访问它:
((MainWindow)Application.Current.MainWindow).btnNext
But it does look messy, and from what I've read is not considered a best practice. Anyone able to provide an answer that constitutes a best practice for Accessing controls / properties from the current instance of a MainWindow - or any other active windows / views for that matter?
但它看起来确实很乱,而且从我所读到的内容来看,这并不是最佳实践。任何人都能够提供构成从 MainWindow 的当前实例访问控件/属性的最佳实践的答案 - 或任何其他与此相关的活动窗口/视图?
回答by mm8
You can get a reference to the parent window of the UserControl using the Window.GetWindow method. Call this once the UserControl has been loaded:
您可以使用 Window.GetWindow 方法获取对 UserControl 的父窗口的引用。加载 UserControl 后调用此方法:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
this.Loaded += (s, e) =>
{
MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
if (parentWindow != null)
{
//...
}
};
}
}
You could also access all open windows using the Application.Current.Windows property:
您还可以使用 Application.Current.Windows 属性访问所有打开的窗口:
MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
Which one to use depends on your requirements. If you want a reference to the application's main window for some reason, you could stick with your current approach. If you want a reference to the parent window of the UserControl, using the Window.GetWindow method would be better.
使用哪一种取决于您的要求。如果出于某种原因想要引用应用程序的主窗口,则可以坚持使用当前的方法。如果要引用 UserControl 的父窗口,使用 Window.GetWindow 方法会更好。
The best practice is generally to use the MVVM design pattern and bind UI controls to source properties of a view model that may be shared by several views. But that's another story. You could refer to the following link for more information about the MVVM pattern: https://msdn.microsoft.com/en-us/library/hh848246.aspx
最佳实践通常是使用 MVVM 设计模式并将 UI 控件绑定到可能由多个视图共享的视图模型的源属性。但那是另一个故事了。您可以参考以下链接以获取有关 MVVM 模式的更多信息:https: //msdn.microsoft.com/en-us/library/hh848246.aspx

