How to center and scale Silverlight applications using ViewBox control
- by Jacek Ciereszko
There are many ways to make your application scalable in Web Browser window and align it in the center. Usually we use two Grid controls to align and panel control (like Canvas) to scale our apps.
Not the best solution
<UserControl … >
<Grid x:Name="LayoutRoot" Background="White">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<Canvas x:Name="scalePanel" VerticalAlignment="Top" HorizontalAlignment="Center">
…
</Canvas>
</Grid>
</Grid>
</UserControl>
The example above usually works but there are better ways. How? Use ViewBox. ViewBox control contains scale mechanisms with some stretching options. So ViewBox together with Grid control is all what we need to align and scale our applications.
Good solution
<UserControl … >
<Grid x:Name="LayoutRoot" Background="White">
<Viewbox>
...
</Viewbox>
</Grid>
</UserControl>
How to find ViewBox control
For those applications created in Silverlight 4, ViewBox is available in plug-in. For applications created in Silverlight 3 you can find it in Microsoft Silverlight Toolkit.
Demo
Let’s create a simple application that will contain: Button, TextBlock and red Rectangle. It will also have some Margin settings. This application won’t be in the center of window and it will not scale.
<UserControl … >
<Grid x:Name="LayoutRoot">
<Grid Margin="100, 50, 100, 20">
<StackPanel Orientation="Horizontal">
<Button Width="100" Height="100" Content="test"/>
<TextBlock Text="Button" Width="100" Height="100" />
<Rectangle Width="100" Height="100" Fill="Red"/>
</StackPanel>
</Grid>
</Grid>
</UserControl>
Run demo: RUN
But If we use ViewBox control, we will got centered and always scaled application.
<Grid x:Name="LayoutRoot">
<Viewbox>
<Grid Margin="100, 50, 100, 20">
<StackPanel Orientation="Horizontal">
<Button Width="100" Height="100" Content="test"/>
<TextBlock Text="bottom" Width="100" Height="100" />
<Rectangle Width="100" Height="100" Fill="Red"/>
</StackPanel>
</Grid>
</Viewbox>
</Grid>
Link to application: RUN (try to resize application’s window)
Link to source code: SilverlightCenterApplication.zip
References
ViewBox for Silverlight 3 http://silverlight.codeplex.com/
Polish version: http://jacekciereszko.pl/2010/05/jak-wysrodkowac-i-skalowac-aplikacje.html
Jacek Ciereszko