Get a Reference to MainPage in a Silverlight Application

Get a Reference to MainPage in a Silverlight Application

by JBrooks 30. November 2010 08:57

Once the user was logged in I wanted to change the menu options that are shown.  To do this I had to get a reference to MainPage.  Here is the code for that:

    MainPage m;
    if (Application.Current.RootVisual.GetType().Name == "BusyIndicator")
        m = (MainPage)((BusyIndicator)Application.Current.RootVisual).Content;
        m = (MainPage)Application.Current.RootVisual;

The code below was a PREVIOUS TRY, but didn’t work because sometimes I would get an exception because the first Parent was null.  Didn’t have time to look into this, and thought the code had some value so I left it here for now.

========= PREVIOUS TRY ============================================================

First I created a static method in the App class that walks up the hierarchy of parents until it finds a match.  This can be used for more than just finding MainPage.  Everything in the hierarchy should be derived from the FrameworkElement class.

public static FrameworkElement GetParentByName(FrameworkElement currentPage, string ParentName)
            FrameworkElement fe = (FrameworkElement)currentPage.Parent;
            // Walk your way up the chain of Parents until we get a match
            while(fe.GetType().Name != ParentName)
                fe = (FrameworkElement)fe.Parent;
            return fe;

Then in the page Home I have the following code that calls that method.

private void Page_LayoutUpdated(object sender, System.EventArgs e)
    if (WebContext.Current.User.IsAuthenticated)
        MainPage m = (MainPage)App.GetParentByName(this, "MainPage");
        m.LinkResetPassword.Visibility = System.Windows.Visibility.Collapsed;
        m.LinkChangePassword.Visibility = System.Windows.Visibility.Visible;



Comments (2) -

Johann Brazil
10/10/2011 11:31:17 AM #

Just to make things a little bit easier, I've created a property read-only and adjusted your code a little:

public MainPage MainPage
                if (App.Current.RootVisual.GetType().Name == "BusyIndicator")
                    return (MainPage)((System.Windows.Controls.BusyIndicator)App.Current.RootVisual).Content;
                    return (MainPage)App.Current.RootVisual;

JBrooks United States
10/11/2011 12:01:52 PM #

Cool, thanks.