ContentPresenter的绑定内容

时间:2014-02-27 09:32:14

标签: c# .net wpf xaml visual-studio-2012

我正在制作custom label

Border CornerRadius="10"  Background="#428bca" Height="{TemplateBinding Height}" Width="{TemplateBinding Width}">
        <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" >
            <TextBlock.Foreground>
                White
            </TextBlock.Foreground>
        </ContentPresenter>
    </Border>

我希望以这样的方式绑定ContentPresenter的内容,当我更改内容的长度时,边框的size(宽度和高度)将自动调整,以便我不会不必手动更改它。

1 个答案:

答案 0 :(得分:1)

以下标签应该做你想要的。请注意,如果它是例如在Grid中,您必须将对齐属性设置为默认Stretch的其他值,否则Panel将调整Label的大小(例如,它所占用的Grid单元格的大小)。

<Label Content="Hello, World."
       BorderBrush="Black"
       BorderThickness="2"
       HorizontalAlignment="Left"
       VerticalAlignment="Top">
    <Label.Template>
        <ControlTemplate TargetType="Label">
            <Border CornerRadius="10" Background="#428bca"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
                <ContentPresenter Margin="{TemplateBinding Padding}"
                    Content="{TemplateBinding Content}"
                    ContentTemplate="{TemplateBinding ContentTemplate}"/>
            </Border>
        </ControlTemplate>
    </Label.Template>
</Label>

为了对所有标签重用此ControlTemplate,您可以将其置于默认的标签样式中:

<Style TargetType="Label">
    <Setter Property="HorizontalAlignment" Value="Left"/>
    <Setter Property="VerticalAlignment" Value="Top"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Label">
                <Border CornerRadius="10" Background="#428bca"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <ContentPresenter Margin="{TemplateBinding Padding}"
                        Content="{TemplateBinding Content}"
                        ContentTemplate="{TemplateBinding ContentTemplate}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>