装饰UserControl WPF

时间:2011-02-15 08:59:04

标签: wpf user-controls contentcontrol

我想在以下组中装饰一些控件:

<UserControl x:Class="Infrastructure.UI.ItemsGroup" ... >
    <Border BorderBrush="Black" BorderThickness="1" CornerRadius="5" Background="Red">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="25" />
            </Grid.RowDefinitions>
            <ContentPresenter Grid.Row="0" />
            <TextBlock x:Name="ctrlGroupText" Grid.Row="1" HorizontalAlignment="Center" />
        </Grid>
    </Border>
</UserControl>

并在其他XAML文件中使用它,例如:

<Grid Grid.Column="0">
    <UI:ItemsGroup GroupText="Hello World">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Button>1111</Button>
            <Button>1111</Button>
        </Grid>
    </UI:ItemsGroup>
</Grid>

但它不起作用。我错了什么? :) 感谢

1 个答案:

答案 0 :(得分:3)

您需要修改UserControl的模板,而不是将Border添加为儿童

<UserControl x:Class="Infrastructure.UI.ItemsGroup" ... >
    <UserControl.Template>
        <ControlTemplate TargetType="{x:Type UserControl}">
            <Border BorderBrush="Black" BorderThickness="1" CornerRadius="5" Background="Red">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="25" />
                    </Grid.RowDefinitions>
                    <ContentPresenter Grid.Row="0" />
                    <TextBlock x:Name="ctrlGroupText" Grid.Row="1" HorizontalAlignment="Center" />
                </Grid>
            </Border>
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

<强>更新

要将TextBlock的文字设置为GroupText,您可以使用绑定

<TextBlock x:Name="ctrlGroupText"
           Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ItemsGroup}},
                          Path=GroupText}"
           Grid.Row="1"
           HorizontalAlignment="Center" />