As I mentioned before, I’ve been doing some work in WPF recently (actually, I was doing it in Silverlight, but I abandoned that due to some of the security limitations - I wanted to be able to launch Word from my app and then communicate between my Silverlight app and a Word add-in I was developing, but that wasn’t possible [you can’t start processes from Silverlight], so I’ve switched to a WPF app deployed via ClickOnce which is probably close enough.)
Aaaaanyway (that was a rather long set up for the rest of my post which is actually pretty to-the-point!), my Word add-in is also WPF and I am using the hosting feature of WinForms to link my VSTO add-in to the WPF controls and so on. So far, it’s been a magical experience, but I ran into a problem when trying to create a “theme” for my app (the default WPF theme is fugly!).
I found this post on Dr. WPF’s blog, and it explained one way to get application-level resources in a hosted environment (you basically just have to create the Application object yourself).
The only problem was that one of the buttons I have in my Ribbon opens a WPF window. If you then closed that window and clicked the button to open it again, you would get the following exception:
The fix was actually on that post that I linked to, but since it was in the comments, way down the bottom, I missed it on my first look. Anyway, the answer was that I had to set the ShutdownMode correctly on the application, like so:
(The fully-qualified type names are required since VSTO has an Application property that was otherwise interfering)
If you don’t set ShutdownMode correctly, the default action is that the first window to be opened is designated as the “main” window, and so when the main window closes, WPF will shut down the Application object as well. By setting it to OnExplicitShutdown, you have to remember to explcitly call Application.Shutdown, but at least we have explicit control over when it happens.