Search code examples
c#wpfuser-controlsapp.xaml

Applicaiton object is coming null in ViewModel in wpf, trying to access Application variables


I am working on WPF application which contains two usercontrols, i am trying to set a Application variable and assigning some value at viewModel loads. This viewmodel is bind with my UserControl.

Question is how can i get and set the APplication variables in wpf. Whatever i have tried i am writing below.

App.xaml.cs

public string globalText = "";
public bool isNewUser;
public App()
{
    isNewUser = true;
}


MyViewModel.cs

App currentApp = Application.Current.Windows.OfType<App>().FirstOrDefault();

or

App currentApp = (App)System.Windows.Application.Current;

Above both ways i have tried but in both ways i am getting CurrentApp null.

i tried to add some value as below.

if(currentApp.IsNewUser)
{
   CurrentApp1.globalText = "Hello World";
} 

Solution

  • I am getting exception System.InvalidCastException: 'Unable to cast object of type 'SecondProject.App' to type 'FirstProject.App'.' While syntax App thisApp = ((App)Application.Current); is written in FirstProject.

    If you have two App classes in scope you could reference the correct one using its fully qualifed type name:

    App thisApp = (FirstProject.App)Application.Current;