2012-05-22 71 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}"/>