When a Silverlight application is embedded in a web page, users expect it to stretch or shrink gracefully as the browser window changes size. Out of the box, the plug-in’s ActualWidth and ActualHeight only report the size of the Silverlight surface itself, not the surrounding viewport. To make the UI truly responsive we need to:
- Read the live dimensions of the browser window.
- Re-flow the layout every time the user resizes the page.
Reading the browser dimensions from Silverlight
Silverlight cannot directly query the browser’s viewport size, but JavaScript can. We expose a managed method that JavaScript will invoke whenever the size changes. Mark the method with [ScriptableMember] so it is callable from the browser.
[ScriptableMember]
public void Reflow(string width, string height)
{
double w = double.Parse(width, CultureInfo.InvariantCulture);
double h = double.Parse(height, CultureInfo.InvariantCulture);
// keep a small margin
const int margin = 8;
// scrollable planning area
PlanScrollViewer.Width = w - margin;
PlanScrollViewer.MaxHeight = h - 54;
// reposition floating elements
Canvas.SetLeft(ButtonPanel, w - 400);
Canvas.SetLeft(TitleText, w / 2 - 150);
// center the progress overlay
Canvas.SetLeft(ProgressOverlay, w / 3);
Canvas.SetTop (ProgressOverlay, 80);
Canvas.SetZIndex(ProgressOverlay, 999);
}
Hooking the resize event once
Rather than duplicating JavaScript on every page, we register the handler from managed code during the root visual’s Loaded event.
private void Root_Loaded(object sender, RoutedEventArgs e)
{
// Build a one-liner that wires up the resize handler.
string script =
@"setTimeout(function () {
var ctl = document.getElementById('silverlightControl');
var update = function () {
ctl.Content.MainPage.Reflow(
document.documentElement.clientWidth,
document.documentElement.clientHeight);
};
update(); // initial call
window.onresize = update; // keep in sync
}, 1000);";
HtmlPage.Window.Eval(script);
}
The one-second delay gives the plug-in time to finish instantiating before the first measurement. After that, every resize triggers the Reflow method, ensuring the Silverlight interface always fills the available space without scrollbars or clipped content.