Search code examples
c#uwpwin-universal-appwindows-10-universal

How can correctly I get MainPage?


I first tried MainPage rootPage = new MainPage(), but this throws an error.

So I tried the official sample version:

[MainPage.xaml.cs]

namespace theMain
{
    public sealed partial class MainPage : Page
    {
        public static MainPage Current;

        public class MainPage()
        {
            this.InitializeComponent();
            Current = this;
        }

        public async void theFunctionIneedToAccess(P1, P2)
        {
            // Update the variable in MainPage and update the UI as well
        }
    }
}

[OtherCode.cs]

using theMain

namespace theOther
{
    public sealed partial class OtherClass
    {
        MainPage rootPage = MainPage.Current; //In debugging mode, I found that I get null here

        private void SmthHappening()
        {
            theFunctionIneedToAccess(P1, P2);
        }
    }
}

This at least does not throw an error, but I ALWAYS GET rootPage = null for this.

I tested unifying the namepsaces (i.e. namespace theMain for both), but this did not help.

What am I doing wrong here????

Any help is appreciated! :)


Solution

  • By your definition, MainPage.Current gets an instance of the currently loaded MainPage.

    If your MainPage.Current is always null, please check whether the MainPage is already loaded in the Frame. When you try to get the MainPage.Current before the MainPage is loaded, the Current has not been assigned at this time, of course, it will be displayed as null.

    In the OnLaunched method in App.xaml.cs, there is such a piece of code:

    if (e.PrelaunchActivated == false)
    {
        if (rootFrame.Content == null)
        {
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }
        Window.Current.Activate();
    }
    

    Please make sure you call the method of MainPage.Current after this code finishes executing.

    Best regards.