Monday, 20 June 2011

Close SharePoint Modal Dialog from within Silverlight

This took me a fair bit of searching to figure out, and there’s probably a number of better (or at least different) ways of doing this, but this seems to work for me, it’s just a few lines of code, it’s non-invasive, and you don’t have to tweak the page hosting your Silverlight object. 

So… imagine you’ve got a Silverlight application running inside of a SharePoint modal dialog.  You want to allow the user to click a button in Silverlight (say, a “Save” button after saving some data to some web service using WCF), to dismiss the modal dialog.

This is simply a combination of two techniques, shown here and here.  You’d put this code in the code-behind of your user control, e.g. MainPage.xaml.cs.  Using MVVM you could bind an ICommand to your button, or if you’re not using MVVM, you could just put this in the Click event of a button in the code behind.

 public void CloseWindow()
     var Script = HtmlPage.Document.CreateElement("script" );
     Script.SetAttribute("type", "text/javascript" );
     Script.SetProperty("text", "function CloseDialog() { window.frameElement.commitPopup(); }" );
     HtmlPage.Window.Invoke("CloseDialog" );