Home > front end >  How can I get a non-static field from the main App.xaml.cs class via App.Current in WPF?
How can I get a non-static field from the main App.xaml.cs class via App.Current in WPF?

Time:06-07

I need to get a non-static field from App.xaml.cs class, but i don't know how.

this is my code from App.xaml.cs containing the IsUserLoggedIn field:

public partial class App : Application
{
    internal bool IsUserLoggedIn { get; private set; }
}

and this is the code calling the IsUserLoggedIn field from my EventTable.cs class:

internal class EventTable
{
    private void UpdateEvents()
    {
        if (App.Current.IsUserLoggedIn) // here is an error: "Applcation"
        {                               // does not contain the definition
                                        // of "IsUserLoggedIn"
        }
    }
}

CodePudding user response:

App.Current is the same static property as Application.Current and has declared Application type. you need to cast it to App. I suggest to do it this way:

public partial class App : Application
{
    internal bool IsUserLoggedIn { get; private set; }

    public static App Instance
    {
        get { return Current as App; }
    }
}

then use it in condition:

internal class EventTable
{
    private void UpdateEvents()
    {
        if (App.Instance.IsUserLoggedIn)
        {

        }
    }
}
  • Related