2012-05-22 68 views
1

我想创建一个模板,我可以反复使用一个窗体上的按钮。创建一个按钮模板

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

但可悲的是,这并不工作。有没有其他的模板,我应该用它来传递文本值?

回答

2

为了使它工作,有一个控件ContentPresenter。将其放置在您想要的模板内。但请记住,它可能是任何东西,文本,图像或其他一些控件,并且您的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内使用时,像按钮,自动附加到模板化亲本的ContentContentTemplateContentTemplateSelector性质。

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

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

<Button ContentTemplate="{StaticResource myButtonContentTemplate}"/>