应用程序.Current和App.Current为空

本文关键字:Current 为空 App 应用程序 | 更新日期: 2023-09-27 18:08:25

我正在创建一个应用程序(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总是null。

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

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

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

我的问题是,我是否必须创建一个新的Dispatcher对象,或者我缺少了什么。我所要做的就是更新我的GUI,而线程正在运行。

应用程序.Current和App.Current为空

汉斯·帕桑特评论回答

WPF的正常入口点是Main()。它是自动生成的,用于创建App.xaml类实例,很难看到。入口点不再是外接程序中的Main(),现在是启动事件处理程序。你需要自己创建应用实例。样板代码为http://stackoverflow.com/a/2694710/17034

应用程序。

作为一种解决方法,你可以这样做:

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

然后在viewmodel中:

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

如果您试图从Winforms应用程序打开WPF应用程序,则应用程序。Current为空。应用程序。Current仅是WPF应用程序的特性,而不是Winforms。你可以试试下面的链接:

为什么应用程序。当前== null在一个WinForms应用程序?