5

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)

Ming Slogar
  • 2,327
  • 1
  • 19
  • 41
  • 1
    In most cases works Window.GetWindow(this) but there is an pitfall when you use for example an Behavior then you have to do Window.GetWindow(AssociatedObject) – LWS Apr 09 '22 at 06:00

2 Answers2

7

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);    
Tony
  • 16,527
  • 15
  • 80
  • 134
  • 2
    The urls are useful, I was looking for the namespace of 'Window'. var ownerWindow = System.Windows.Window.GetWindow(this); – CRice May 18 '15 at 03:44
4

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.

Slugart
  • 4,535
  • 24
  • 32
  • If these two statements are just accessing properties, then the number of windows I had would be negligible. Am I correct? – Ming Slogar Sep 22 '13 at 00:47
  • Correct. Pointing out the one window was more for the correctness of the approach. I.e. if you have multiple windows only one will be the MainWindow whilst different windows can be returned by GetWindow (obviously). – Slugart Sep 22 '13 at 00:50
  • Yeah, I know about the single MainWindow. I just wanted to clarify for future reference. – Ming Slogar Sep 22 '13 at 00:52