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
[Scriptable] is in
System.Windows.Browser). Then, in the page loaded method, register the scriptable methods using
Now we can call
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
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.
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.
ScaleTransform and set
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.