Thursday, July 26, 2018

Set ControlTemplate TemplateBinding in Code

Leave a Comment

I want to set the Foreground in the code behing file. But setting Foreground doesn't change the visual style. FontSize btw works?

<ControlTemplate  x:Key="SimpleBtn" TargetType="Button">       <Button x:Name="btnct" CommandParameter="{Binding Content}" Command="{Binding Path=DataContext.ButtonClickCommand,ElementName=MainGrid}"          keyImageProperty:KeyPressed.Image="{DynamicResource ResourceKey=gbutton70x70}" keyImageProperty:KeyNotPressed.Image="{DynamicResource ResourceKey=button70x70}"           Template="{DynamicResource ResourceKey=KeyboardButton}" Content="{TemplateBinding Content}"           FontSize="{TemplateBinding FontSize}" FontWeight="Medium" Foreground="{TemplateBinding Foreground}" FontFamily="{TemplateBinding FontFamily}"  />  </ControlTemplate>   <DataTemplate x:Name="btndatatemplate" x:Key="itemContDataTemplate" >       <Button x:Name="btnstandard" Template="{DynamicResource ResourceKey=SimpleBtn}"                                                    FontWeight="Bold"                   Content="{Binding Content}"     />   </DataTemplate> 

1 Answers

Answers 1

This should work for setting up templatebinding on the button in code behind (as part of a complete ControlTemplate definition):

var button = new FrameworkElementFactory(typeof(Button)) { Name = "btnct" }; button.SetValue(Button.ForegroundProperty, new TemplateBindingExtension(Button.ForegroundProperty)); 

FontSize works not because the templatebinding is working, but because FontSize is automatically inherited by child controls, whereas foreground is not. (Try the following in XAML:)

<Button FontSize="20" Foreground="Red">      <Button Content="Click"/> </Button> 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment