1

同様の構造を使用する複数のUserControlXAMLファイルがあります。この重複を削除し、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>
4

2 に答える 2

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 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>
于 2012-12-05T15:13:11.017 に答える
0

おそらく、コントロールの基本クラスとしてContentControlを使用する必要があります(ユーザーコントロールではなくカスタムコントロールである必要があります)。

そうすれば、その中で定義ControlTemplateして使用できるようになりますContentPresenterContentコントロールのコンテンツを定義するには、コントロールのプロパティを設定する必要があります。

于 2012-12-05T14:12:51.430 に答える