Strange behavior with Silverlight when showing modal dialogs in SharePoint

Recently I have been working seriously on integrating Silverlight applications in SharePoint. I already have some experience with SharePoint but with my everyday work I discover more and more “features” of that system.

The Scenario

Everything started with a scenario I had to implement within SharePoint and ended up to be related just to Silverlight. So, my scenario involves creating a small Silverlight application, which is displayed within a web part. This application requires showing a modal dialog, which hosts another application. As my web part may be placed in small space, I preferred to use SharePoint’s dialog feature instead of using ChildWindow. Those two Silverlight applications (the one in the web part and the one in the dialog) communicate via local message infrastructure, which Silverlight provides.

The Problem

In FireFox everything works correctly. However, that is not the case with Internet Explorer. In IE 8 (I guess it’s valid for every version of that browser) I discovered that the web part application does not receive any message from the one in the dialog. Not only the Silverlight application in the web part does not receive any messages, but it is unloaded (wtf?). When I close the dialog, it is loaded again. I could easily check that by putting a breakpoint at the Application.Startup and Application.Exit events. I managed to debug the JavaScript code used to show the dialog by SharePoint (NOTE: Kids, do not do this at home! Debugging SharePoint’s scripts may harm your health!) and noticed that when a dialog is shown, all object elements in the HTML page are made hidden (via CSS visibility). Of cource, when the dialog is closed, these elements are again returned to life (I mean, shown on the web page). After testing that scenario separately I realized that, only in IE, a Silverlight application gets reloaded when its corresponding object element is being made hidden and then visible again. Searching desperately I found this was a known bug and it even had a workaround.

The Solution

The issue concerns only the active Silverlight application, the one which is currently focused. The solution is pretty simple – before hiding the application, you have to change the focus. In my case, before calling my JavaScript function, which opens the modal dialog, I change the focus by calling window.focus().