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?
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 yourButtonnor your ControlTemplate, should not care about what it is.The
ContentPresenter, when used inside aContentControl, like the button, automatically attaches to theContent,ContentTemplateandContentTemplateSelectorproperties of the templated parent.Now if you want to display more than just Text, or want to customize the text more, just pass a
DataTemplateas yourContentTemplatedirectly to the specific button.