by Viper
26. December 2008 09:13
A lot of time we develop content for silverlight applications that depend on size of browser or host application. Silverlight framework exposes some of host application's settings through System.Windows.Interop.SilverlightHost object which are accessible through Host property of Application class of your silverlight application. One of the properties of System.Windows.Interop.SilverlightHost object is System.Windows.Interop.Content. You can subscribe to Resized event of this object to be notified whenever there is a change in browser window.
You can find the value of browser window size from ActualWidth and ActualHeight property of Content object. When host application resizes, silverlight application gets notified through Resized event. You can subscribe to this event when application startup completes. Always access these size values in Resized event because this is time in rendering workflow when these values are actually known. These values are not known before this event. Silverlight framework uses two step process to resize UI elements. In first pass it calculates the sizes and positions. And in second step it actually positions the elements based on calculated sizes. And then final calculations have completed, then actual sizes are known.
private void Application_Startup(object sender, StartupEventArgs e)
{
startPage = new HostInfomation();
this.RootVisual = startPage;
this.Host.Content.Resized += new EventHandler(Content_Resized);
}
private void Content_Resized(Object sender, EventArgs e)
{
HostInfomation hostInfoPage = this.startPage as HostInfomation;
hostInfoPage.LayoutRoot.Children.Clear();
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = Orientation.Vertical;
TextBlock heightBlock = new TextBlock();
heightBlock.Text = string.Format("Height = {0}", this.Host.Content.ActualHeight);
TextBlock widthBlock = new TextBlock();
widthBlock.Text = string.Format("Width = {0}", this.Host.Content.ActualWidth);
stackPanel.Children.Add(heightBlock);
stackPanel.Children.Add(widthBlock);
hostInfoPage.LayoutRoot.Children.Add(stackPanel);
}