I have a few buttons to set up in c# WPF, and I like to use a button template. I can set the template and then use it in my grid, but how do I change the text of the TextBox per button and also other properties like the color of the rectangle?
Here is my template:
<Window.Resources>
<ControlTemplate x:Key="menuButton_Type1" TargetType="Button">
<Grid >
<Rectangle x:Name="Normal" Fill="#FFFDC776" HorizontalAlignment="Left" Height="25" Width="82" RadiusX="7" RadiusY="7"/>
<Rectangle x:Name="Pressed" Fill="White" HorizontalAlignment="Left" Height="25" Width="82" RadiusX="7" RadiusY="7" Visibility="Hidden"/>
<Rectangle x:Name="Disable" Fill="#FF707070" HorizontalAlignment="Left" Height="25" Width="82" RadiusX="7" RadiusY="7" Visibility="Hidden"/>
<Border Width="82" Height="25" Padding="0,0,5,0">
<TextBlock Text="EXIT" FontFamily="{StaticResource Swiss911}" FontSize="18" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Normal" Property="Visibility" Value="Hidden" />
<Setter TargetName="Pressed" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Normal" Property="Visibility" Value="Hidden" />
<Setter TargetName="Disable" Property="Visibility" Value="Visible" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
I use the template button in my XAML grid like this:
<Grid>
<Button Template="{StaticResource menuButton_Type1}" Margin="18,226,-18,-226" />
</Grid>
I would like to change the text of the TextBlock currently set to "EXIT" and also the color of one of the Rectangle, in this case the normal one. How do I do this?
I tried to use dynamic propreties, that did not work for me.
CodePudding user response:
Magny,
I found your answer in this pages :
- What is the template binding vs binding?
- https://docs.microsoft.com/tr-tr/dotnet/desktop/wpf/advanced/templatebinding-markup-extension?view=netframeworkdesktop-4.8
You can simply put binding to Text property of texblock on your ControlTemplate.
You should add the Content property of button to TextBlock's text property :
<TextBlock Text="{TemplateBinding Content}" FontFamily="{StaticResource Swiss911}" FontSize="18" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
Then you can set the content property of Button, the Content property of Button will be passing to the Your Texblocks Text property.
<Button Template="{StaticResource menuButton_Type1}" Content="Exit" Margin="100" />
I tested whit these Buttons :
<Button Template="{StaticResource menuButton_Type1}" Content="Exit" Margin="0,0,0,0" />
<Button Template="{StaticResource menuButton_Type1}" Content="Close" Margin="100,0,0,0" />
<Button Template="{StaticResource menuButton_Type1}" Content="Open" Margin="200,0,0,0" />