I want to bind Border.Background in my Button ControlTemplate to the Background Property of my button. Usually I would use a 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 the error: "Cannot set TemplateBinding if not in a Template".. But I am in a Template! (It works if I dont use LinearGradientBrush and bind the borders Backround Property directly to {TemplateBinding Background}....
As @Snowbear said, you should bind Color
to Color
and not Color
to Brush
. But in his solution, TemplateBinding
with deep property Path
such as Foreground.Color
isnt allowed as part of the 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.
I think you might have some other error here, but it is not reported well. GradientStop
accepts a Color
in its corresponding property while Background
and Foreground
properties of a Button
are brushes, not colors. If you think that Background
and Foreground
will be SolidColorBrush
you might try accessing their Color
property in your binding, but I'm not sure whether it will work or not:
<GradientStop Color="{TemplateBinding Foreground.Color}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With