使用ControlTemplate覆盖XAML WPF中的Button不显示内容

时间:2013-05-06 06:27:55

标签: c# wpf xaml

我是XAML新手,正在看这个博客

http://jeremybytes.blogspot.com/2009/03/wpf-xaml-sample.html

他提到“请注意,他们没有任何内容(Button1a,Button1b等)。这是因为我们的模板不包含内容的元素。”我想弄清楚即使应用了新的按钮模板后内容仍然保持不变。这是XAML

<Page.Resources>
    <ControlTemplate TargetType="Button" x:Key="targetButton">
        <Canvas Width="100" Height="100" Name="mainCanvas">
            <Rectangle Height="100" Width="100" Fill="Aqua" Canvas.Top="1"/>     
        </Canvas>
    </ControlTemplate>        
    <Style TargetType="Button">
        <Setter Property="Margin" Value="5, 5, 5, 5"/>            
        <Setter Property="Template" Value="{StaticResource targetButton}"/>
    </Style>
</Page.Resources> 
<StackPanel DataContext="{Binding Board}">
    <StackPanel Orientation="Horizontal">
        <Button Name="testButton1a" Click="testButton1a_Click" Content="testButton1a"/>
        <Button Name="testButton1b" Click="testButton1a_Click" Content="testButton1b"/>
        <Button Name="testButton1c" Click="testButton1a_Click" Content="testButton1c"/>
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Button x:Name="testButton2a" Click="testButton1a_Click" Content="testButton2a"/>
        <Button x:Name="testButton2b" Click="testButton1a_Click" Content="testButton2b"/>
        <Button x:Name="testButton2c" Click="testButton1a_Click" Content="testButton2c"/>
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Button Name="testButton3a" Click="testButton1a_Click" Content="testButton3a"/>
        <Button Name="testButton3b" Click="testButton1a_Click" Content="testButton3b"/>
        <Button Name="testButton3c" Click="testButton1a_Click" Content="testButton3c"/>
    </StackPanel>
</StackPanel>

我曾尝试在模板中添加TextBlock,但我看到所有按钮上都覆盖了相同的文本块。我想要的是渲染testButton *内容显示在矩形按钮矩阵上,这样我就可以在点击后更改内容。

谢谢,任何帮助将不胜感激

1 个答案:

答案 0 :(得分:8)

您可以使用ContentPresenter显示内容:

<ControlTemplate TargetType="Button" x:Key="targetButton">
   <Canvas Width="100" Height="100" Name="mainCanvas">
      <Rectangle Height="100" Width="100" Fill="Aqua" Canvas.Top="1"/>
      <ContentPresenter/>
   </Canvas>
</ControlTemplate>