[英]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. 我正在包含两个用户控件的WPF应用程序上工作,我试图设置一个Application变量并在viewModel加载时分配一些值。 This viewmodel is bind with my UserControl.
该视图模型与我的UserControl绑定。
Question is how can i get and set the APplication variables in wpf. 问题是如何在wpf中获取和设置APplication变量。 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. 在我尝试过的两种方法之上,但在两种方法中,我都得到CurrentApp null。
i tried to add some value as below. 我试图增加一些价值如下。
if(currentApp.IsNewUser)
{
CurrentApp1.globalText = "Hello World";
}
I am getting exception
System.InvalidCastException
: 'Unable to cast object of type 'SecondProject.App' to type 'FirstProject.App'.'我收到异常
System.InvalidCastException
:'无法将类型为'SecondProject.App'的对象转换为类型为'FirstProject.App'。 While syntaxApp thisApp = ((App)Application.Current);
而语法
App thisApp = ((App)Application.Current);
is written in FirstProject.是用FirstProject编写的。
If you have two App
classes in scope you could reference the correct one using its fully qualifed type name: 如果您在范围内有两个
App
类,则可以使用其完全限定的类型名称来引用正确的一个:
App thisApp = (FirstProject.App)Application.Current;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.