【问题标题】:Applicaiton object is coming null in ViewModel in wpf, trying to access Application variables应用程序对象在 wpf 的 ViewModel 中为空,试图访问应用程序变量
【发布时间】: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&lt;App&gt;() 没有意义,因为它试图在当前应用程序的 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


【解决方案1】:

我收到异常System.InvalidCastException:'无法将'SecondProject.App'类型的对象转换为'FirstProject.App'类型。'而语法App thisApp = ((App)Application.Current); 是用FirstProject 编写的。

如果您有两个 App 范围内的类,您可以使用其完全限定的类型名称引用正确的类:

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

【讨论】:

  • 需要对我的问题进行投票,我的问题是正确的。请投票,它对我有用,非常感谢。
  • 完成了,先生! :)
猜你喜欢
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 2011-12-04
  • 2021-02-15
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
相关资源
最近更新 更多