Question

I have written a WordAddIn that allows the user to call on some metadata for the current document. Via a custom button in the ribbon, they can call a WPF. The WPF calling is realized as follows:

        System.Windows.Application app = null;

and then in the method called by the button:

if (app == null)
{
    app = new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
    app.Run();
}
MainWindow win = new MainWindow(graph);
app.Dispatcher.Invoke((Action)(() => { win.Show(); }));

The first time the button is clicked after Word started, nothing happens and it becomes impossible to edit content in the word document. The second time the button is clicked the WPF object loads and is shown, this works for any button click afterwards too. So it seems the first time the dispatcher is called, it hangs. How do I prevent this?

Was it helpful?

Solution 2

I got help with this in the Microsoft WPF forums. Creating and calling app in a new thread does the trick, as app does indeed block the current thread it is called in.

                    if (app == null)
                    {
                        Thread thread = new Thread(new ThreadStart(() =>
                            {
                                app = new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
                                autoResetEvent.Set();
                                app.Run();
                            }));
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                    }
                    else 
                    {
                        autoResetEvent.Set();
                    }
                    autoResetEvent.WaitOne(); //wait until app has been initialized on the other thread
                    app.Dispatcher.Invoke((Action)(() => { new MainWindow(graph).Show(); }));                       
                    }

OTHER TIPS

I'm not sure why you want to dispatch the call anyway since this is the same thread. You only need to marshall calls to UI thread when the "current" thread is not a UI thread, which is not your case - you only have one thread.

Secondly, Application.Run is a blocking method and should not be called in the Add-In context. You can't create a WPF application inside Add-In application. BTW, Application.Run always runs on the current thread, which in your case is the same one Word Add-In runs on. And this how it is supposed to be.

If I understand you correctly, you are creating a WPF application because you don't want to use WinForms technology but WPF. Do it without Application.Run and do not dispatch calls because there is no reason to do so.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top