Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Button in XAML WPF with ControlTemplate does not display content

Tags:

c#

wpf

xaml

I am a XAML newbie and was looking at this blog

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

He mentions "Notice that they do not have any content (Button1a, Button1b, etc.). This is because our template does not contain an element for the Content." I am looking to figure out how ensure the content remains even after the new button template is applied. Here is the 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>

I have tried to add a TextBlock in the template but I see the same textblock overlayed across all buttons. All I want is to render testButton* content displayed on the rectangle button matrix so I can change the content once clicked.

Thanks, any help will be appreciated

like image 935
Yam Avatar asked May 06 '13 06:05

Yam


1 Answers

You can use the ContentPresenter to display the content:

<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>
like image 117
Florian Gl Avatar answered Oct 20 '22 14:10

Florian Gl