【问题标题】:using a ControlTemplate to reduce duplication between multiple UserControls使用 ControlTemplate 减少多个 UserControls 之间的重复
【发布时间】:2012-12-05 14:08:26
【问题描述】:

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

但显然不能覆盖 UserControl 的模板。

我怎样才能做到这种干净的方式?派生自其他东西,然后是 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>

【问题讨论】:

    标签: silverlight xaml user-controls


    【解决方案1】:

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

    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>
    

    【讨论】:

      【解决方案2】:

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

      然后您将能够定义ControlTemplate 并在其中使用ContentPresenter。比你需要为你的控件设置Content 属性来定义控件的内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多