wpf Application.Current.MainWindow 与 Window.GetWindow(this)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18939176/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:41:51  来源:igfitidea点击:

Application.Current.MainWindow vs. Window.GetWindow(this)

c#wpf

提问by Ming Slogar

I need to access the window which hosts a given control (thisin the following code snippet).

我需要访问承载给定控件的窗口(this在以下代码片段中)。

Assuming that I have only one window in my application, which of the following statements is less resource intensive? (Or is there perhaps a better way to do this?)

假设我的应用程序中只有一个窗口,以下哪个语句占用的资源较少?(或者可能有更好的方法来做到这一点?)

Application.Current.MainWindow

Application.Current.MainWindow

Window.GetWindow(this)

Window.GetWindow(this)

采纳答案by Slugart

If you only have one window then either option is fine - performance wise there is not much difference between them. Application.Current.MainWindow will simply return a field of type Window that is stored on the current application whilst Window.GetWindow() will access the value of a dependency property. Neither are very expensive to execute.

如果您只有一个窗口,那么任何一个选项都可以 - 从性能上看,它们之间没有太大区别。Application.Current.MainWindow 将简单地返回存储在当前应用程序中的 Window 类型的字段,而 Window.GetWindow() 将访问依赖项属性的值。两者的执行成本都不是很高。

回答by Tony

Some people do not optimize until needed. Anyway on this case the resource or performance penalty is probably minimal. In other words, you probably don′t need to worry, you will have other things to optimize.

有些人在需要时才进行优化。无论如何,在这种情况下,资源或性能损失可能很小。换句话说,您可能不必担心,您还有其他事情需要优化。

This will return or set the Main Window of the Application:

这将返回或设置应用程序的主窗口:

// http://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow.aspx
var w = Application.Current.MainWindow;    

Use this to return a reference to the Window the control is located:

使用它返回对控件所在窗口的引用:

// http://msdn.microsoft.com/library/vstudio/system.windows.window.getwindow.aspx
Window.GetWindow(theDependencyObject);

You said that you need to access the window which hosts a given control. Then I think that the more appropriate semantically is:

您说您需要访问承载给定控件的窗口。然后我认为在语义上更合适的是:

Window.GetWindow(theDependencyObject);