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)
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With