Search code examples
c#wpfxaml

C# call NavigationService from .cs Class in WPF


i am writing a program using WPF (C#, XAML). In there i have a page called "Startup", one called "error" and also a class called "accessHandler.cs". The accessHandler continuously checks for some bool (can only be done from accessHandler), and if this bool returns true, i need the accessHandler to navigate to page "error". I tried multiple things:

-Having "error" as a UserControl (copied the XAML into a UserControl) and trying to load it into MainGrid in "Startup". This did not work as i have no way (that i know of) to get the currently displayed instance of "Startup". Therefore i could not add "error" to "Startup"'s MainGrid. I could not think of a way to get the currently displayed instance of Startup into the accessHandler.

-Having errorPage as a Page and trying to navigate to it from the accessHandler. However i can not use the NavigationService inside of the accesshandler because again i dont have the active "Startup"-instance in there. -Creating a new Startup instance and then using it to navigate to the page returned the following error: "Object reference not set to an instance of an object." The piece of exact code to reproduce this error:

       `error errInst = new error();
        Startup st = new Startup();
        st.NavigationService.Navigate(errInst);`

My problem could be solved by: Either finding a way to get the currently displayed instance of "Startup" into the accessHandler as soon as it finds the bool to be true Or finding a way to navigate to "errorPage" from the accessHandler without needing the currently displayed instance of "Startup"

Thanks in advance!


Solution

  • The answer turned out to be pretty simple. Let "Startup" be the page that is shown when the other page is supposed to be loaded from another class called AccessHandler. You need a reference inside of said class which looks like this:

    public static Startup st;
    

    And in the main-function of startup you just declare said reference like this:

    AccessHandler.st = this;
    

    You can then use "st" in AccessHandler as usual, for my purpose for instance like this:

    st.NavigationService.Navigate(new alert());