I've been using Silverlight quite a lot lately and ran into some Silverlight control sizing issues while using MVVM. The control being set to 100% width within the aspx page was causing issues. Googling some, I saw several solutions, but none that were that descriptive. To address my needs, I needed the silverlight control on the aspx page to resize based on dynamic changes within my framed MainPage. Luckily, my frame for the simple project I'm working on is consuming the entire control, so there's no calculation needed to come up with the total control dimensions.
The basics of the approach were that I used some simple javascript for resizing the silverlight control on the page, passing in the updated height of the silverlight control.
function ResizeObject(height) {
try {
var slobject = document.getElementById("silverlightObject");
slobject.style.height = height + "px";
window.status = slobject.style.height;
}
catch (err) { }
}
I then needed to invoke this javascript on the page from within silverlight control itself. Since I'm using MVVM and the Navigation Framework, my MainPage has a NavigationFrame on it. I used the Navigated event on the NavigationFrame to get when the contents of the NavigationFrame have changed and used the Content property of the NavigationEventArgs within the event to get the control that it's being changed to. I wire up an LayoutUpdated event to that control so I get when the internal control's layout is changing so I can change the "on the page" silverlight control's height (since this was specifically my issue). Here's the code, enjoy!
void MainPage_Loaded(object sender, RoutedEventArgs e) {
NavigationFrame.Navigated += new NavigatedEventHandler(NavigationFrame_Navigated);
}
private double _lastHeight = 0.0;
void NavigationFrame_Navigated(object sender, NavigationEventArgs e) {
FrameworkElement element = e.Content as FrameworkElement;
element.LayoutUpdated += (sender2, e2) => {
if (element.RenderSize.Height > 0.0 && _lastHeight != element.RenderSize.Height) {
HtmlPage.Window.Invoke("ResizeObject", new object[] { element.RenderSize.Height });
_lastHeight = element.RenderSize.Height;
}
};
}
I eliminate unecessary updates to the control size by validating the Height is > 0 and I keep the state of the last height to make sure I'm not setting it to the existing size.
Jeff