XAML重用一个标记块

时间:2016-01-24 20:10:13

标签: c# wpf xaml

考虑我有多个页面,我想要显示相同的"标题"在每个页面没有复制&多次粘贴它:它非常难以维护。

    <!--  #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  -->

使这个标记块可重用的选项有哪些?例如,写这样的东西会很好:

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

1 个答案:

答案 0 :(得分:4)

用户控件是一种选择。

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>