I have created an office add-in that holds an instance of a WPF Application. When the user clicks buttons on the add-in, I launch different windows by doing the following:
MyViewModel viewModel = new MyViewModel(string infoFromOffice);
MyWindow view = new MyWindow();
view.DataContext = viewModel;
wpfApp.Run(view);
In constructing view models before my call to wpfApp.Run() I hit probelms with the current SynchronizationContext later on. The answer here explains why. Is there a better way of launching WPF windows from an office add-in?
While Arthur’s answer helped point to why the problem was happening, it did not actually answer how to pass data to a view model from a host application while still having the view model constructor call be after the call to
App.Run(). I have since found a (very simple) solution! For anyone who is interested.In App.xaml.cs:
When launching the app:
Note that the startup URI needs to be removed in App.xaml. This very simple solution allows me to pass information to my app, but at the same time does not require that the view model be constructed in a “non WPF environment” and so can make use of the Dispatcher etc.