Francesco Bonizzi
Francesco Bonizzi

Reputation: 5302

XAML Reuse a block of markup

Consider I have multiple pages and I want to show the same "Header" in every page without copying & pasting it multiple times: it's very unmaintainable.

    <!--  #region Header  -->

    <Grid Grid.Row="0">

        <Rectangle Style="{StaticResource HeaderBackground}" />
        <TextBlock 
                   Style="{StaticResource PageTitle}"
                   Text="Page1" />
        <Button 
                Content="Settings"
                Command="{Binding GotoSettingsPage}" />

    </Grid>

    <!--  #endregion Header  -->

What are the options to make this block of markup reusable? For example it would be nice to write something like this:

<MyHeader Grid.Row="0" PageTitle="Page1" />

Upvotes: 4

Views: 373

Answers (1)

user1325543
user1325543

Reputation: 531

A user control is an option.

MyHeader.Xaml:

<UserControl
    x:Class="App1.MyHeader"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid>
        <Rectangle Style="{StaticResource HeaderBackground}" />
        <TextBlock x:Name="Title"
                   Style="{StaticResource PageTitleStyle}"
                   Text="" />
        <Button Content="Settings"
                Command="{Binding GotoSettingsPage}"/>
    </Grid>
</UserControl>

MyHeader.Xaml.cs:

using Windows.UI.Xaml.Controls;

namespace App1
{
    public sealed partial class MyHeader : UserControl
    {
        public MyHeader()
        {
            this.InitializeComponent();
        }

        public string PageTitle
        {
            get { return Title.Text; }
            set { Title.Text = value ?? ""; }
        }
    }
}

MainPage.Xaml:

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <local:MyHeader PageTitle="Page 1"/>
    </Grid>
</Page>

Upvotes: 5

Related Questions