MasterPage and Silverlight
I have seen several post about how to implement MasterPage in Silverlight 2.0, most of the posts are about using “fixed” UserControls and dynamically change the content of a control in code-behind. Here is another solution where a Template will be used instead.
In Silverlight we can use the ContentControl to add a child element to it:
<ContentControl>
<Button Content="test"></Button>
</ContentControl>
The ContentControl has a Template property we can use to specify the Template of the ContentControl. To create a template we can for example use the <Style> element within the App.xaml (Only to make it global).
<Application.Resources>
<Style x:Name="myMasterPage" TargetType="ContentControl">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Grid Height="300" Width="400">
<Grid.RowDefinitions>
<RowDefinition Height="55"/>
<RowDefinition Height="*"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<Button Content="Button 1" Click="Button_Click"></Button>
<Button Content="Button 2" Click="Button_Click_1"></Button>
<Button Content="Button 3" Click="Button_Click_2"></Button>
</StackPanel>
<ContentPresenter Grid.Column="1" Content="{TemplateBinding Content}"></ContentPresenter>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</Application.Resources>
The Style will target the ContentControl and also set the Template property of the ContentControl. The Template property will have a child element of type ControlTemplate which can be used to define a template. We will use the <Style> and <ControlTemaplate> to define our MasterPage. The <ContentPresenter> can be used in a similar way as <ContentPlaceholder> is used within a ASP.Net MasterPage. The Content of the <ContentPresenter> will be the Content from the <ContentControl> which will use the “myMasterPage” template.
Note: If we add an event to the template, it will be added to the App’s code-behind.
To use the “myMasterPage” template in our Page.xaml we simply add a <ContentControl> and set it's Style property to the “myMasterPage´” style:
<UserControl x:Class="SilverlightApplication1.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"> <ContentControl Style="{StaticResource myMasterPage}"> <Button Content="test"></Button> </ContentControl>
</UserControl>
The content of the ContentControl, will now be located where the ContentPresenter is in the “myMasterpage” template.