【发布时间】:2018-08-21 09:13:51
【问题描述】:
我正在开发包含两个用户控件的 WPF 应用程序,我正在尝试设置一个应用程序变量并在 viewModel 加载时分配一些值。此视图模型与我的 UserControl 绑定。
问题是如何在 wpf 中获取和设置应用程序变量。无论我尝试过什么,我都写在下面。
App.xaml.cs
public string globalText = "";
public bool isNewUser;
public App()
{
isNewUser = true;
}
MyViewModel.cs
App currentApp = Application.Current.Windows.OfType<App>().FirstOrDefault();
或
App currentApp = (App)System.Windows.Application.Current;
以上两种方式我都尝试过,但两种方式都让 CurrentApp 为空。
我尝试添加一些价值如下。
if(currentApp.IsNewUser)
{
CurrentApp1.globalText = "Hello World";
}
【问题讨论】:
-
Application.Current.Windows.OfType<App>()没有意义,因为它试图在当前应用程序的 Windows 集合中查找应用程序。也就是说,如果 isNewUser 和 globalText 都在 App 类中,为什么视图模型需要打扰它。将该逻辑留在 App 类中。 -
我检查了它,它确实有效。 ((App)Application.Current)
-
如果我在写 App thisApp = ((App)Application.Current);它正在捐赠给我在同一解决方案中添加的另一个项目。我必须在一个解决方案中进行项目。 FirstProject 由 SecondProject 使用。因此,如果我在 FirstProject 的类中编写上述语法,它将自动表示为 SecondProject。这对我来说很奇怪,但它正在发生。
-
为什么要投反对票?奇怪!
-
我收到异常 System.InvalidCastException:'无法将'SecondProject.App'类型的对象转换为'FirstProject.App'类型。'虽然语法 App thisApp = ((App)Application.Current);是用 FirstProject 编写的。
标签: c# wpf user-controls app.xaml