【问题标题】:Creating a button Template创建按钮模板
【发布时间】:2012-05-29 05:02:57
【问题描述】:

我正在尝试为我可以在表单上反复使用的按钮创建一个模板。

Button,我希望它包含一个有两行的Grid,并在底行中包含一段自定义文本。

这是我到目前为止所得到的,但我认为它不正确,因为我想从按钮元素中设置文本。

<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>

然后调用我希望我可以去的模板:

<Button Content="This is the text" />

但遗憾的是,这不起作用。我应该使用其他模板将文本值传递给它吗?

【问题讨论】:

    标签: c# wpf templates button text


    【解决方案1】:

    为了使其工作,有一个名为ContentPresenter 的控件。将它放在模板中您想要的任何位置。但请记住,它可以是任何东西,文本、图像或一堆其他控件,而您的 Button 或 ControlTemplate 不应该关心它是什么。

    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>
    

    ContentPresenter 在 ContentControl 中使用时,就像按钮一样,会自动附加到模板化父级的 Content、ContentTemplate 和 ContentTemplateSelector 属性。

    现在,如果您想要显示的不仅仅是文本,或者想要更多地自定义文本,只需将 DataTemplate 作为您的 ContentTemplate 直接传递给特定按钮即可。

    <DataTemplate x:Key="myButtonContentTemplate">
        <TextBlock FontSize="18" Text="{Binding}"/>
    </DataTemplate>
    
    <Button ContentTemplate="{StaticResource myButtonContentTemplate}"/>
    

    【讨论】:

      猜你喜欢
      • 2011-06-05
      • 2011-04-04
      • 2010-11-18
      • 2010-12-28
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      相关资源
      最近更新 更多