This article is compatible with the latest version of Silverlight.
This tip is about adjusting the size of the Silverlight object in the Html to the size of the content in our Silverlight application. The example I will use will manipulate only the height, because the width can be manipulated in analogical way.
Let's start with explanation of how we're going to access the Silverlight object in the HTML. We use the HtmlPage object in the codebehind. With its help we invoke a javascript function, which will deal with Silverlight object in the mark up:
private void ResizeSilverlightOnject( double height )
{
HtmlPage.Window.Invoke( "ResizeObject", new object[] { height } );
}
The function is placed in the markup and is called ResizeObject. It takes as parameter the desired height. Note that to declare the Silverlight plug-in I use a div and an object element. Here it is:
function ResizeObject( height )
{
var host = document.getElementById( "silverlightControlHost" );
host.style.height = height + "px";
}
We simply get the div that hosts the Silverlight object and set the height in its style property to the passed height. If you don't want the div to be smaller than the content area of the browser the function should look like that:
function ResizeObject( height )
{
var host = document.getElementById( "silverlightControlHost" );
if( document.documentElement.clientHeight < height )
{
host.style.height = height + "px";
}
else
{
host.style.height = document.documentElement.clientHeight.toString() + "px";
}
}
Here we use the clientHeight property of the documentElement. It returns the size of the height of the content area of the browser. We compare it to the passed height and in dependance of the result we set the div's height either to the height sent as function's argument or to the clientHeight.
That's it, not hard at all. Hope it solves some problems. Here is also a very simple demo and its source code if you want to see this tip in action. Notice that when the content of the grid grows bigger than the content area of the browser the browser's scrollbar appears. Of course it can be used in other cases. For example a silverlight control placed in the mark up can also be resized depending on the content in it like Silverlightshow's Highlights control.