Reputation: 1867
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";
}
Upvotes: 1
Views: 666
Reputation: 169340
I am getting exception
System.InvalidCastException
: 'Unable to cast object of type 'SecondProject.App' to type 'FirstProject.App'.' While syntaxApp 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;
Upvotes: 1