How to derive from a base page in Silverlight

[This post comes to you curtsey of Windows Live Writer – an excellent blogging tool, and the code snippets are from the Paste from Visual Studio plugin.]

Say you want to have a base page XAML that offers some functionality, and you’d like to keep that functionality but insert your own. For example, you want to write XAML for a window with a title bar, border, and a close window icon, and then you want to write XAML for the different content that will be displayed inside the window. The different content XAMLs can be swapped in and out and they take advantage of the base XAML that provides the title bar, border, and close window functionality.

We’ll create a base XAML called say, DemoControl.xaml (which derives from UserControl), this XAML contains the titlebar and the close icon (no border to keep it simple),

<UserControl x:Class="DemoControl"
    <Canvas x:Name="LayoutRoot">
        <Canvas x:Name="Toolbar" Opacity="1.0">
            <Canvas x:Name="TitleBar" Background="Brown" Margin="0,-40" Height="40" Width="200" />
            <Image x:Name="CloseIcon" Margin="180,-40" Height="32" Width="32" Source="delete.png" />

Then we’ll create the derived control called say About.xaml, that derives from DemoControl,

<Demo:DemoControl x:Class="About"

<!--Make sure you include the namespace of the DemoControl!—>

We can’t put any XAML inside About.xaml, but we can inject another XAML via code, (in About.xaml.cs do this),

Canvas cv = (Canvas)this.FindName("LayoutRoot");
StreamResourceInfo sri = Application.GetResourceStream(
                         new Uri("Demo;component/XamlFiles/AboutContent.xaml", UriKind.Relative));
using (TextReader tr = new StreamReader(sri.Stream))
    String url = tr.ReadToEnd();
    UserControl rootObject = XamlReader.Load(url) as UserControl;
    rootObject.Name = "test";
    Canvas cd = (Canvas)rootObject.FindName("LayoutRoot");

Where AboutContent.xaml, could be any XAML derived from UserControl,

    Width="400" Height="300">
    <Canvas x:Name="LayoutRoot" Height="631" Width="450" Background="White">
        <!—Place any content here!—>

Thus, we can insert AboutContent.xaml into the derived page About.xaml and have the titlebar and closeicon show up without AboutContent.xaml having to write or wire that code.

Digg This

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: