Centered Silverlight 2.0 Content

by edsilverton

A very common layout for Flash sites is to center a rectangle of content horizontally and vertically in the browser window.

centered

I noticed that a method for doing this for Silverlight using css was posted here: http://michaelsync.net/2008/03/17/tipstricks-how-to-center-silverlight-control-on-a-webpage

This approach is good but I thought I’d suggest an alternative more in keeping with our particular way of working.

For Flash sites we tend to prefer to make the movie fill the entire window and then use actionscript to center the rectangle rather than css. We’ve found that the extra screen real-estate for Flash to redraw doesn’t significantly effect performance because of Flash’s “dirty rectangles” system. It’s also worth noting that the full-browser approach is a common practice for many Flex apps.

Here’s a simple way of getting this effect in Silverlight.

Set the width and height properties of your Silverlight control to 100%. Then in the root UserControl create a (scale 9) Grid like this:

<UserControl x:Class=”LayoutRoot”
xmlns=”http://schemas.microsoft.com/client/2007&#8243;    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”&gt;
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width=”*”/>
            <ColumnDefinition Width=”800″/>
            <ColumnDefinition Width=”*”/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height=”*”/>
            <RowDefinition Height=”600″/>
            <RowDefinition Height=”*”/>
        </Grid.RowDefinitions>      
       
<Canvas Grid.Column=”1″
           Grid.Row=”1″>
            <!– Content goes here –>
        </Canvas>
    </Grid>
</
UserControl>

Leave the root UserControl’s width and height properties blank so it stretches to fill the available space.

Update:

In order to get rid of the default margins of your page so the Silverlight control fills it completely you could use css like the following:

   
/* hide from ie on mac \*/
html {
   
height: 100%;
   
overflow: hidden;
    }

#SilverlightControlHost {
   
height: 100%;
   
width: 100%;
    }
/* end hide */

body {
   
height: 100%;
   
margin: 0;
   
padding: 0;
    }

This is the same as the css we use for Flash sites except the div wrapping the plugin has been renamed “SilverlightControlHost”.

About these ads