Reputation: 960
I am making a 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>
I want to bind the content of ContentPresenter
in such a way that ,when I change the length of the content , size
(width and height) of border will get automatically adjust so that i don't have to change it manually.
Upvotes: 2
Views: 3462
Reputation: 128146
The following Label should do what you want. Note that if it is a child of e.g. a Grid, you have to set the alignment properties to some other value that the default Stretch
, because otherwise the Label will be resized by the Panel (for example to the size of the Grid cell that it occupies).
<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>
In order to reuse this ControlTemplate for all your Labels, you might put it in a default Label style:
<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>
Upvotes: 2