Ming Slogar
Ming Slogar

Reputation: 2357

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

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

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

Window.GetWindow(this)

Upvotes: 6

Views: 26092

Answers (2)

Tony
Tony

Reputation: 17657

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);    

Upvotes: 8

Slugart
Slugart

Reputation: 4680

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.

Upvotes: 4

Related Questions