1

私の Silverlight 4 アプリケーションでは、単純なユーザー コントロールを作成したいと考えています。このユーザー コントロールには、他のものに加えて、別のコントロールを含めることができます。私が欲しいものの例は、Border-Control です。Border-Control に他のユーザー コントロールが含まれ、そのコンテンツが表示されるように、他のコントロール (正確に 1 つの他のコントロール) を Border-Control に配置できます。その機能を備えたユーザー コントロールを作成するには、何をする必要がありますか? アイデアは、他のコントロールを次のようにユーザー コントロールのContentPresenterに配置することです。

<Grid x:Name="LayoutRoot">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition />
  </Grid.RowDefinitions>

  <TextBlock x:Name="TextBlockHeader" Text="{Binding Title, ElementName=userControl}" HorizontalAlignment="Left" Foreground="White" Margin="5,0"/>
  <ContentPresenter x:Name="ContentPresenterObject" Grid.Row="1" />
</Grid>

さて、(Expression Blend で) 子コントロールを UserControl に追加できるようにするにはどうすればよいでしょうか。それともこれは間違ったアプローチですか?

前もってありがとう、
フランク

4

1 に答える 1

2

ContentControl から継承するカスタム コントロールを作成することをお勧めします。これは、 UserControls とカスタム コントロールについて話している素敵なブログ投稿です。

xaml を定義する "Generic.xaml" と、クラスを定義する cs クラスを作成する必要があります。

public class CustomControl: ContentControl
{
    public CustomControl()
    {
        this.DefaultStyleKey = typeof(CustomControl);
    }
}

xaml クラスは次のようになります。

<ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyApp">

<Style TargetType="local:CustomControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:CustomControl">
                <Grid x:Name="LayoutRoot">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock x:Name="TextBlockHeader" Text="{Binding Title,
                               ElementName=userControl}" HorizontalAlignment="Left" 
                               Foreground="White" Margin="5,0"/>
                    <ContentPresenter x:Name="ContentPresenter" Grid.Row="1"
                                      Content="{TemplateBinding Content}"
                                      ContentTemplate="{TemplateBinding ContentTemplate}"
                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                      HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

于 2012-05-23T17:02:03.727 に答える