创建一个按钮模板 [英] Creating a button Template

查看:99
本文介绍了创建一个按钮模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创造一个按钮,我可以在窗体上再次使用遍地的模板。

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?

推荐答案

要使它的工作,有一个叫做控制内容presenter 。无论你希望它是将你的模板中。但请记住,它可以是任何东西,文本,图像或一群其他控件,你的按钮和你的控件模板,不应该关心它是什么。

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>

内容presenter ,内使用​​时, ContentControl中,Like按钮,会自动连接到该内容的ContentTemplate ContentTemplateSelector 模板化父属性。

The ContentPresenter, when used inside a ContentControl, like the button, automatically attaches to the Content, ContentTemplate and ContentTemplateSelector properties of the templated parent.

现在,如果你需要的不仅仅是文本,以显示更多或想自定义文本越多,只是通过一个的DataTemplate 为你的的ContentTemplate 直接到特定的按钮。

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

这篇关于创建一个按钮模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆