Override button in XAML WPF with ControlTemplate does not display content

I am new to XAML and have watched this blog

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

He mentions, "Please note that they do not have content (Button1a, Button1b, etc.). This is because our template does not contain an element for Content." I want to figure out how to ensure that content is saved even after applying the new button template. Here is 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 tried to add a TextBlock to the template, but I see the same text block superimposed on all buttons. All I want to do is display the contents of testButton * displayed on the matrix of the rectangle's buttons so that I can change the contents after clicking.

Thanks, any help would be appreciated

+6
source share
1 answer

You can use ContentPresenter to display 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> 
+8
source

Source: https://habr.com/ru/post/944342/


All Articles