WPF best practice to get current MainWindow instance?

15,062

You can get a reference to the parent window of the UserControl using the Window.GetWindow method. Call this once the UserControl has been loaded:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
        this.Loaded += (s, e) =>
        {
            MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
            if (parentWindow != null)
            {
                //...
            }
        };
    }
}

You could also access all open windows using the Application.Current.Windows property:

MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();

Which one to use depends on your requirements. If you want a reference to the application's main window for some reason, you could stick with your current approach. If you want a reference to the parent window of the UserControl, using the Window.GetWindow method would be better.

The best practice is generally to use the MVVM design pattern and bind UI controls to source properties of a view model that may be shared by several views. But that's another story. You could refer to the following link for more information about the MVVM pattern: https://msdn.microsoft.com/en-us/library/hh848246.aspx

Share:
15,062

Related videos on Youtube

ganjeii
Author by

ganjeii

SOreadytohelp

Updated on September 15, 2022

Comments

  • ganjeii
    ganjeii over 1 year

    I got a warning that this may be a subjective question and might be closed, but I'm going to ask anyway.

    I'm basically trying to access a button on my MainWindow in a WPF application from a UserControl that gets loaded up from within the MainWindow.

    I'm currently accessing it like this from the UserControl's code behind:

    ((MainWindow)Application.Current.MainWindow).btnNext
    

    But it does look messy, and from what I've read is not considered a best practice. Anyone able to provide an answer that constitutes a best practice for Accessing controls / properties from the current instance of a MainWindow - or any other active windows / views for that matter?

  • Kelly
    Kelly over 7 years
    If your accessing the main window often I would consider making it static reference somewhere. ie: using a singleton or something similar.