Resizing a Silverlight canvas
Let’s say you want your Silverlight canvas to resize to fill the browser window, or at least to fill its container.
I expected to find a simple way of defining what happens when the canvas container is resized. Something similar to the Loaded attribute. But it’s a little more complicated than that. We need to handle the event in JavaScript and call our managed code to do the actual resizing from there.
First we set up the managed code to make it callable from JavaScript. To do this you need include to add the [Scriptable] tag to your class and all methods that will be called from JavaScript ([Scriptable] is in System.Windows.Browser). Then, in the page loaded method, register the scriptable methods using WebApplication.Current.RegisterScriptableObject.
Now we can call Resize from JavaScript. All we have to do is set up the event handler. But you can’t declare the event handler in the events section of Silverlight.createObjectEx. I decided to use an old-fashioned JavaScript event handler:
This works when the window is resized, but it won’t work if the canvas container is resized for some other reason. I’ll get to a better solution in a minute, but first let’s look at how it works, because we’re going to keep the contents of the function.
SilverlightControl is the id of the Silverlight object, as defined in the createObjectEx call. Content.basic.Resize is created in the C# code above. “basic” could be anything, but I stuck with what I saw in the tutorial I read.
This almost gets the job done, but it’s better to use the Silverlight resize event. The only way I could find to do this is to set it up in JavaScript after the Silverlight object is created.
onLoad is the function called when the object is created, as specified in the createObjectEx call. And Content.onResize is the resize handler, which unfortunately isn’t in Intellisense, but is in the MSDN article on Silverlight resizing, which appears to be very incomplete and incorrect.
Now just create another JavaScript function with the same code as the resize handler above, and we’re good to go. All that’s left is to actually resize the canvas and the objects. If you just want everything to scale with the canvas, you can use a ScaleTransform and set ScaleX and ScaleY in the C#. The XAML:
And the C#:
In this case, the canvas starts at 640×480, so our scale factors are based on those numbers.

That’s all there is to it. Here is the project I made, which includes a slightly more complex Resize method.