How to size the Silverlight plugin dynamically

October 28, 2011 2 comments

What is the problem?

 

From time to time you will find you need to embed a Silverlight plugin in another ASP.Net application. Creating a user experience that is the same as other ASP.Net pages in the application can be tricky.

Setting the plugin to width and height 100% will result in your plugin being cut off when the height is beyond that of the browser since the browser will not show its scrollbars if your plugin’s height is larger. Setting the plugin to a specific height might leave large blank spaces at the bottom of the plugin if you make certain parts of your page visible/invisible based on a specific criteria, like showing an entry for Products where the Entity type is a Business.

 

What is the solution?

 

We need to dynamically size the body tag of the host html page when the size of the plugin changes. This can happen when controls on a SL page is made invisible or moving between pages in the Navigation framework where the pages are different in size.

 

How do we do that?

 

Javascript side

On your MasterPage or otherwise where the the Plugin is hosted, give your HTML body tag an id like “theBody”, then add this javascript method in the head of your HTML page.

//Javascript on your MasterPage or where the SL PLugin is hosted
function ChangePageSize(pageSize) {
document.getElementById(“theBody”).style.height = pageSize + “px”;
}

Silverlight side

In the constructor of your Silverlight control/page subscribe to the LayoutRoot or Control/Page’s SizeChanged event handler:

//This is required on every page to resize dynamically
LayoutRoot.SizeChanged += new SizeChangedEventHandler((s, e) => HtmlPage.Window.Eval(String.Format(“ChangePageSize({0});”, e.NewSize.Height)));

Categories: Silverlight