Reputation: 23680
I'm trying to create a template for a button that I can use over and over again on a form.
The Button
, I want it to contain a Grid
with two rows and a custom piece of text within the bottom row.
This is what I've got so far, but I don't think it's right because I want to set the text from within the button element.
<ControlTemplate TargetType="Control">
<Grid Width="444">
<Grid.RowDefinitions>
<RowDefinition Height="51" />
<RowDefinition Height="36" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#286c97"></Grid>
<Grid Grid.Row="1" Background="#5898c0">
<TextBlock Grid.Row="1" FontFamily="Segoe UI" FontSize="12" Text="{TemplateBinding Content}" />
</Grid>
</Grid>
</ControlTemplate>
Then to call the template I was hoping I could go:
<Button Content="This is the text" />
But sadly this doesn't work. Is there some other template that I'm supposed to be using to pass the text value to it?
Upvotes: 1
Views: 360
Reputation: 11051
To make it work, there is a control called ContentPresenter
. Place that inside your template wherever you want it to be. But remember, that it could be anything, a text, an image or a bunch of other controls, and your Button
nor your ControlTemplate, should not care about what it is.
ControlTemplate TargetType="Control">
<Grid Width="444">
<Grid.RowDefinitions>
<RowDefinition Height="51" />
<RowDefinition Height="36" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#286c97"></Grid>
<Grid Grid.Row="1" Background="#5898c0">
<ContentPresenter/>
</Grid>
</Grid>
</ControlTemplate>
The ContentPresenter
, when used inside a ContentControl
, like the button, automatically attaches to the Content
, ContentTemplate
and ContentTemplateSelector
properties of the templated parent.
Now if you want to display more than just Text, or want to customize the text more, just pass a DataTemplate
as your ContentTemplate
directly to the specific button.
<DataTemplate x:Key="myButtonContentTemplate">
<TextBlock FontSize="18" Text="{Binding}"/>
</DataTemplate>
<Button ContentTemplate="{StaticResource myButtonContentTemplate}"/>
Upvotes: 2