Application.Current.RootVisual is always a null reference


  • I'm trying to reference MainPage.xaml from another page.

    However this reference is always null! 



    MainPage mp = Application.Current.RootVisual as MainPage;

    if (mp == null)

    MessageBox.Show("can't find RootVisual");   //this will show everytime



    <UserControl x:Class="MyProject.MainPage">

    <Grid x:Name="LayoutRoot" Width="1000" VerticalAlignment="Top" HorizontalAlignment="Left">

    <navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}" Grid.Row="1" Source="/Home">




    Monday, February 22, 2010 9:27 PM


All replies

  • Check your App.xaml.cs whether the RootVisual has been loaded there or not.

    Monday, February 22, 2010 9:41 PM
  •  Are you sure you set MainPage as your Application.RootVisual in the App.xaml.cs? 



    Monday, February 22, 2010 9:44 PM
  • I thought I tried that but the program didn't work then.  

    private void Application_Startup(object sender, StartupEventArgs e) {

    this.Resources.Add("WebContext", WebContext.Current);


    this.RootVisual = new Page();    //if I add this line to App.xaml.cs then the program just loads a blank page


    Update just realized I needed to use  this.RootVisual  = new MainPage()!   This works now.


    Monday, February 22, 2010 9:49 PM
  • I have 2 projects where I access Application.Current.RootVisual.

    In one of them (normal Silverlight App) it is returning null and the other (Naviagtion Silverlight App) it is returning the correct value. Both the App.cs have the same kind of details. ie


     private void Application_Startup(object sender, StartupEventArgs e)
                this.RootVisual = new MainPage();

     I am so lost???



    Thursday, March 11, 2010 9:58 AM
  • You have two Silverlight projects each has App.cs so it means you have two Silverlight application Projects. Each has a Application start point.

    Do you mean when you run one Application, you can access Application.Current.RootVisual.

    When you run another application (this one has nothing to do with the first one), your Application.Current.RootVisual is null?

    Or do you mean you used one project as class library of the other project?


    Thursday, March 11, 2010 10:18 AM
  •  can we define Application.Current object in XAML page and use the member/properties from it

    Tuesday, June 08, 2010 6:31 AM
  • I had the same problem.  I was using a RIA services template in VS2010 that had inserted something into my app.xaml that was setting Application.Current.RootVisual as a "BusyIndicator" class.  It then sets the BusyIndicator.Content property to MainPage.  This ended up working for me:

    BusyIndicator bi = Application.Current.RootVisual as BusyIndicator;
    MainPage mp = bi.Content as MainPage;

    Thursday, July 15, 2010 2:31 PM