Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

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)

like image 284
Ming Slogar Avatar asked Sep 22 '13 00:09

Ming Slogar


People also ask

What is MainWindow?

The Main window is the main way to access other windows, load and save files, control trajectory playback, change various global program settings, access help, and to quit the program.

How can I access a control in WPF from another class or window?

If you want to access a control on a wpf form from another assembly you have to use the modifier attribute x:FieldModifier="public" or use the method proposed by Jean. Save this answer.

How do I change the startup window in WPF?

If you look at App. xaml class of your WPF application, you will see the following XAML code. Here the StartupUri sets the startup Window of an application. If you want to change the Startup window to some other window, just change this value.

How do I open MainWindow XAML in Visual Studio?

Once the app is generated, Visual Studio should open the XAML designer pane for the default window, MainWindow. If the designer isn't visible, double-click on the MainWindow. xaml file in the Solution Explorer pane to open the designer.


1 Answers

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);    
like image 50
Tony Avatar answered Oct 12 '22 09:10

Tony