Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF MasterPage

0.00/5 (No votes)
25 May 2009 1  
Create a MasterPage like functionality in WPF with 15 lines of code
WPF Masterpage Image

Introduction

This article shows a way of creating MasterPage-like functionality in WPF with 15 lines of code.

Background

One of the great things in .NET 2.0 was MasterPage. Unfortunately, MasterPage no longer exists in WPF. I have seen a lot of different approaches to achieving ASP.NET MasterPage-like functionality in WPF, with varying levels of complexity. I was not satisfied with any of the techniques and therefore came up with my own approach.

Solution

My solution is Frame. Frames can be used as a kind of content placeholder. "Ding". Surely that must ring a bell.

Using the Code

The sample code was written in C# using Visual Studio 2008 IDE. All the relevant code is in StartPage.xaml and should be self-explanatory. I will summarize the code shown below. You use a DockPanel for your MasterPage layouter. Then you add a first Frame and dock it to the top. Add a second Frame and dock it to the bottom, then add a StackPanel for your navigation (or whatever layout control you fancy) and dock it to the left or right. Finally add a Frame that will contain your content pages. The trick is to set the Source property of that Frame to a Page.

 <Page ...>
     <DockPanel Name="pnlMaster" >
         <Frame Name="frmHeader" DockPanel.Dock="Top" 
		Source="/MasterPages/HeaderPage.xaml" Height="100"></Frame>
         <Frame Name="frmFooter" DockPanel.Dock="Bottom" 
		Source="/MasterPages/FooterPage.xaml"></Frame>
         <StackPanel Name="spnlNavigator" DockPanel.Dock="Left" 
		Width="150" Background="Orange">
             <Button Name="bntContentPage1" Margin="10,10,10,10" 
		Content="Content Page 1" Click="OnClick" 
		CommandParameter="ContentPage1.xaml" />
             
             <Button Name="bntContentPage2" Margin="10,10,10,10" 
		Content="Content Page 2" Click="OnClick" 
		CommandParameter="ContentPage2.xaml" />
          
          </StackPanel>
          <Frame Name="frmMain" Source="/ContentPages/ContentPage1.xaml"></Frame>
     </DockPanel>
     <x:Code>
         <![CDATA[
          void OnClick(object sender, RoutedEventArgs e)
          {
             frmMain.Source = new Uri("/ContentPages/" + 
		((Button)sender).CommandParameter.ToString(), UriKind.Relative);
          }
       ]]>
     </x:Code>
 </Page>

History

  • 25th May, 2009: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here