MyDaftQuestions
MyDaftQuestions

Reputation: 4701

Application.Current and App.Current is null

I'm creating an application (an Office Add-in for Outlook)

The issue I have is updating my screen. I know I need to use invoke the Dispatcher but, it's always null in my 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);
        //});
        });
    }

As you can see, I've tried 2 approaches, but Current is always null.

Oddly, if I use the same code in the code behind of my MainWindow then the following works fine

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

I've read up, the reason is because the MainWindow code behind inherits from Window.

My question is, do I have to create a new Dispatcher object or is there something I'm missing. All I'm trying to do is update my GUI whilst the thread is running.

Upvotes: 7

Views: 15821

Answers (3)

MyDaftQuestions
MyDaftQuestions

Reputation: 4701

Answered in comments by Hans Passant

The normal entrypoint for a WPF is Main(). Which is auto-generated to create your App.xaml class instance, hard to see. The entrypoint is no longer Main() in an add-in, it is now you Startup event handler. So you have to create your app instance yourself. Boilerplate code is http://stackoverflow.com/a/2694710/17034

Application.Current and App.Current is null

Upvotes: 3

shruti singh
shruti singh

Reputation: 166

If you are trying to open a WPF application from a Winforms appliation, Application.Current is null. Application.Current is a feature of WPF applications only and not Winforms. You may try the below link:

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

Upvotes: 2

user1562155
user1562155

Reputation:

As a workaround you could maybe do the following:

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

public static MainWindow AppWindow
{
  get;
  private set;
}

And then in your viewmodel:

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

Upvotes: 2

Related Questions