Search code examples
wpfclassmainwindow

WPF access a page control from MainWindow class


I have created a WPF app that has navigation between two pages. I want a control(a groupbox) from one of the pages to be hidden by default and to be able to enable it when pressing a keycombo. Home1 is the name of the page and bgdb is the name of the groupbox. Home1_Loaded is hooked up to the page loading inside a frame in MainWindow

public void Home1_Loaded(object sender, RoutedEventArgs e)
{
    bdgb.Visibility = Visibility.Collapsed;
}

What modifications need to be done so I can access bgdb from MainWindow class and unhide it via a keycombo (ex Ctrl+B) ? this is the code for mainwindow loading the homepage by default

private void Window_Initialized(object sender, EventArgs e)
{
    Main.Content = new home();
    Main.Navigate(new Uri("home.xaml", UriKind.RelativeOrAbsolute));
}

Solution

  • If you are hosting the Page in a Frame element in the MainWindow, you could cast the Content property of the Frame to Home1 and then access any of its members, e.g.:

    Home1 home1 = e.Content as Home1;
    if (home1 != null)
        home1.bdgb.Visibility = Visibility.Collapsed;
    

    MainWindow.xaml:

    <Frame x:Name="frame" />
    

    You could for example handle the Navigated event for the Frame:

    private void Window_Initialized(object sender, EventArgs e)
    {
        Main.Content = new home();
        Main.Navigated += Main_Navigated;
        Main.Navigate(new Uri("home.xaml", UriKind.RelativeOrAbsolute));
    }
    
    private void Main_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        home home1 = Main.Content as home;
        if (home1 != null)
            home1.bdgb.Visibility = Visibility.Collapsed;
        Main.Navigated -= Main_Navigated;
    }