WPF Bind ControlTemplate content for Property in Control?

I want to associate Border.Background in my Button ControlTemplate with the background Property of my button. I usually used TemplateBinding:

<Style TargetType="Button" x:Key="ColuredButton"> <Setter Property="Background" Value="LightGreen"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border x:Name="Border" CornerRadius="2" BorderThickness="1" BorderBrush="Gray"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="{TemplateBinding Foreground}"/> <GradientStop Color="{TemplateBinding Background}"/> </LinearGradientBrush> </Border.Background> <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> 

But I get an error: "I can not set TemplateBinding, if not in the template." But I am in the template! (It works if I do not use LinearGradientBrush and bind the Backround property to borders directly to {TemplateBinding Background} ....

+4
source share
2 answers

As @Snowbear said, you should bind Color to Color , not Color to Brush . But in his solution, TemplateBinding with a deep Path property such as Foreground.Color is not allowed as part of binding markup.

So use the following ...

  <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="{Binding Foreground.Color, RelativeSource={RelativeSource TemplatedParent}}" Offset="0.2"/> <GradientStop Color="{Binding Background.Color, RelativeSource={RelativeSource TemplatedParent}}" Offset="0.6"/> </LinearGradientBrush> </Border.Background> 

And it should work.

+7
source

I think you may have some other error here, but it is not reported well. GradientStop accepts Color in its corresponding property, and the Background and Foreground a Button properties are brushes, not colors. If you think that Background and Foreground will be SolidColorBrush , you can try to access the Color property in your binding, but I'm not sure if this will work or not:

 <GradientStop Color="{TemplateBinding Foreground.Color}"/> 
+1
source

All Articles