Is it possible to use a converter on a TemplateBinding in XAML?
Asked Answered
C

1

19

I am building a button style that relies on converting a colour brush to a darker shade to create a shadow. In regular XAML I have a converter than I use on the binding that works perfectly:

BorderBrush="{Binding Background, Converter={StaticResource ColourBrushToDarker}}"

But I can't get the converter to work with TemplateBinding in a style definition. Is there a way? Visual Studio just doesn't allow a converter on a TemplateBinding.

I've tried the following with no luck:

Background="{Binding Converter={StaticResource ColourBrushToDarker}, ConverterParameter={Binding Path=Background}}"/>

(And I've tried the above line with TemplateBinding replacing Binding as well as several other iterations)

Can this be done? The other thing I thought of was coding a property in C# that does the conversion, but a style doesn't have a code behind file.

The result I'm after is to be able to create a new brush that is a shade darker than the Background property so the button always has a shadow that is a bit darker than its main background colour.

Clavicorn answered 2/3, 2015 at 1:48 Comment(0)
C
39

After some (tedious) trial and error I have found a solution:

Background="{Binding Background, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource ColourBrushToDarker}}"

I'm still learning XAML styling, but I think what is happening here is that I am able to use Binding as if it were TemplateBinding by setting the relative source to the template parent. Since I'm using Binding (not TemplateBinding), I am able to add a converter and get the desired result.

Clavicorn answered 2/3, 2015 at 2:35 Comment(1)
Note that you can drop the "Mode=" on the RelativeSource as it's optional syntax. i.e: ### Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource ColourBrushToDarker}}" ###Ellerd

© 2022 - 2024 — McMap. All rights reserved.