【问题标题】:Application.Current and App.Current is nullApplication.Current 和 App.Current 为空
【发布时间】:2017-01-31 08:08:33
【问题描述】:

我正在创建一个应用程序(Outlook 的 Office 插件)

我遇到的问题是更新我的屏幕。我知道我需要调用 Dispatcher,但是在我的 ViewModel 中它始终为空

    private ObservableCollection<string> _updates;
    public ObservableCollection<string> Updates
    {
        get { return this._updates; }
        set
        {
            this._updates = value;
            OnPropertyChanged("Updates");
        }
    }


        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += ((s, e) =>
        {
            //logic
            UpdateProgress("Finished");
        });

        bw.RunWorkerAsync();


    private void UpdateProgress(string s)
    {
        //Application.Current.Dispatcher.Invoke(() =>
       // {
        App.Current.Dispatcher.Invoke(() =>
        {            
            this.Updates.Add(s);
        //});
        });
    }

如您所见,我尝试了 2 种方法,但 Current 始终为空。

奇怪的是,如果我在 MainWindow 后面的代码中使用相同的代码,那么以下代码可以正常工作

    private void UpdateProgress(string s)
    {
        Dispatcher.Invoke(() =>
        {
            this.Update = s;
        });
    }

我看过了,原因是因为MainWindow后面的代码继承自Window。

我的问题是,我是否必须创建一个新的 Dispatcher 对象,或者我是否缺少某些东西。我要做的就是在线程运行时更新我的​​ GUI。

【问题讨论】:

  • Application.Current 如果您尝试在非 UI 线程中访问它,则应为 null。您可以将构造函数中对调度程序的引用保存为字段成员,然后在非 UI 线程中使用它。
  • WPF 的正常入口点是 Main()。这是自动生成的以创建您的 App.xaml 类实例,很难看到。入口点不再是加载项中的 Main(),而是您的 Startup 事件处理程序。所以你必须自己创建你的应用程序实例。样板代码is here.
  • @HansPassant,有什么办法可以将此评论移至答案?
  • 只需在您自己的帖子中输入答案,显示您的 Startup 事件处理程序的外观,并将其标记为答案。

标签: c# wpf


【解决方案1】:

由 Hans Passant 在 cmets 中回答

WPF 的正常入口点是 Main()。这是自动生成的以创建您的 App.xaml 类实例,很难看到。入口点不再是加载项中的 Main(),而是您的 Startup 事件处理程序。所以你必须自己创建你的应用程序实例。样板代码是http://stackoverflow.com/a/2694710/17034

Application.Current and App.Current is null

【讨论】:

    【解决方案2】:

    作为一种解决方法,您可以执行以下操作:

    public MainWindow()
    {
      InitializeComponent();
      AppWindow = this; // Here you set the static member to reference this MainWindow.
    }
    
    public static MainWindow AppWindow
    {
      get;
      private set;
    }
    

    然后在您的视图模型中:

    private void UpdateProgress(string s)
    {
      MainWindow.AppWindow.Dispatcher.Invoke(() =>
      {
        this.Updates.Add(s);
        //});
      });
    }
    

    【讨论】:

      【解决方案3】:

      如果您尝试从 Winforms 应用程序打开 WPF 应用程序,Application.Current 为空。 Application.Current 仅是 WPF 应用程序的功能,而不是 Winforms。你可以试试下面的链接:

      Why does Application.Current == null in a WinForms application?

      【讨论】:

      • 不要忽略标签,winforms != wpf.同样在 SO 上,我们将问题作为重复问题关闭,而不是创建带有重复问题链接的新答案。
      • 您需要完整阅读回复。我试图从我之前遇到的事情中帮助这个人;它在 WPF 中,因为我正在从另一个 Winforms 应用程序创建一个 WPF 窗口。不要热衷于投反对票。此外,就结束而言,并不是每个人都可以结束一个问题。您有所需的积分,因此您可以。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      相关资源
      最近更新 更多