Feb 8 2009

How to Popup a Centered Window from inside Silverlight?

Category: silverlight 2.0Bil@l @ 18:48

You have always used JavaScript to pop up Windows from an ASP.NET or HTML page. Now the question comes to my mind, how to show a Popup Window from inside Silverlight territories.

It is so simple! Silverlight contains a class, System.Windows.Browser.HtmlPage, that allows access to the Browser's Document Object Model. It has a method called PopupWindow, that allows a Silverlight developer to open a Popup Window from inside Silverlight.

A sample code can help understand this better:

            HtmlPopupWindowOptions options =
                new HtmlPopupWindowOptions();
            options.Directories = false;
            options.Toolbar = false;
            options.Status = false;
            options.Menubar = false;
            options.Location = false;
            options.Width = 400;
            options.Height = 400;
            options.Top = (Convert.ToInt32(HtmlPage.Window.Eval("screen.height")) - options.Height)/2;
            options.Left = (Convert.ToInt32(HtmlPage.Window.Eval("screen.width")) - options.Width) / 2;
            HtmlPage.PopupWindow(new Uri("http://www.silverlight.net"), "_blank", options);


Notice the bolded words above. The HtmlPopupWindowOptions class allows you to set options for the Window that is to be opened. For example, show/hide the Toolbar, Menubar, etc ...

The HtmlPage.PopupWindow is the method that you can use to show the Popped up Window. It takes as input, a URI representing the URL to open, the target of the Popup Window and finally an instance of the HtmlPopupWindowOptions.

Notice how I used the HtmlPage.Window.Eval method to evaluate ANY JAVASCRIPT code you want. In this case, I wanted to grab the "Screen.Width" and "Screen.Height" to use them to center the Popped up Window.

That's it. Now you have a Centered Popup Window triggered from inside Silverlight application.

Hope this helps,



Comments are closed