代码之家  ›  专栏  ›  技术社区  ›  Ashish-BeJovial

应用程序对象在wpf的ViewModel中为空,正在尝试访问应用程序变量

  •  0
  • Ashish-BeJovial  · 技术社区  · 7 年前

    我正在开发包含两个用户控件的WPF应用程序,我试图设置一个应用程序变量并在viewModel加载时分配一些值。此viewmodel与我的用户控件绑定。

    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 null。

    我试图增加一些价值如下。

    if(currentApp.IsNewUser)
    {
       CurrentApp1.globalText = "Hello World";
    } 
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   mm8    7 年前

    我有个例外 System.InvalidCastException App thisApp = ((App)Application.Current); 写在第一个项目里。

    如果你有两个 App

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