使用ControlTemplate减少多个UserControl之间的重复

时间:2012-12-05 14:08:27

标签: silverlight xaml user-controls

我有多个使用类似结构的UserControl XAML文件。我想删除这个重复,并考虑使用覆盖UserControl的模板的样式(然后使用ContentPresenter作为自定义部分)。

但显然用户控件的模板不能被覆盖。

我这干净的方式怎么样?从其他东西派生出UserControl?

<UserControl x:Class="Class1">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <sdk:Label Grid.Row="0" Content="Title1" Style="{StaticResource Header1}" />
    <Border Grid.Row="1">
    ...
</UserControl>

<UserControl x:Class="Class2">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <sdk:Label Grid.Row="0" Content="Title2" Style="{StaticResource Header1}" />
    <Border Grid.Row="1">
    ...
</UserControl>

2 个答案:

答案 0 :(得分:2)

您可以像这样定义自定义控件。 (我不确定你是否需要指定与内容分开的标题,但这只是以防万一。)

public class MyControl : ContentControl
{
    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(MyControl), new PropertyMetadata(null));

    public string Title
    {
        get { return (string)GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }

    // ... other properties ...
}

然后定义其模板:

<ControlTemplate x:Key="MyControlTemplate" TargetType="mynamespace:MyControl">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <sdk:Label Grid.Row="0" Content="{TemplateBinding Title}" Style="{StaticResource Header1}" />
        <Border Grid.Row="1">
            <ContentPresenter />
        ...
    </Grid
</ControlTemplate>

然后您可以定义默认样式,如下所示。 (或者,你可以给它一个x:Key并在每次使用MyControl时显式设置样式。你也可以在每次使用MyControl时设置Template属性,而不是完全指定这个Style。)

<Style TargetType="mynamespace:MyControl">
    <Setter Property="Template" Value="{StaticResource MyControlTemplate}" />
</Style>

然后使用它:

<mynamespace:MyUserControl Title="Title1">
    <!-- Content here -->
</mynamespace:MyUserControl>

<mynamespace:MyUserControl Title="Title2">
    <!-- Content here -->
</mynamespace:MyUserControl>

答案 1 :(得分:0)

也许您需要使用ContentControl作为控件的基类(它应该不是用户控件而是自定义控件)。

然后,您就可以定义ControlTemplate并在其中使用ContentPresenter。您需要为控件设置Content属性以定义控件的内容。

相关问题