Creating a button Template

戏子无情 提交于 2020-01-16 00:54:31

问题


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?


回答1:


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}"/>


来源:https://stackoverflow.com/questions/10706543/creating-a-button-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!