Can my WPF Style Setter use a TemplateBinding? Can my WPF Style Setter use a TemplateBinding? wpf wpf

Can my WPF Style Setter use a TemplateBinding?


This should work for the case where you're templating a control and you want to bind the value of a property of that control to a property of a different control inside the template. In your case you're templating something (call it MyControl), and that template will include a border whose Padding should be bound to MyControl's padding.

From MSDN documentation:

A TemplateBinding is an optimized form of a Binding for template scenarios, analogous to a Binding constructed with {Binding RelativeSource={RelativeSource TemplatedParent}}.

For whatever reason, specifying TemplatedParent as the source for the binding doesn't seem to work within Style Setters. To get around that you can specify the relative parent to be an AncestorType of the control you're templating (which effectively finds the TemplatedParent providing you haven't embedded other MyControls in the MyControl template).

I used this solution when I was trying to custom template a Button control in which the (String) Content of the Button needed to be bound to the Text property of a TextBlock in the ControlTemplate for the button. Here's what that code looked like:

<StackPanel>    <StackPanel.Resources>        <ControlTemplate x:Key="BarButton" TargetType="{x:Type Button}">            <ControlTemplate.Resources>                <Style TargetType="TextBlock" x:Key="ButtonLabel">                    <Setter Property="Text" Value="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type Button}} }" />                </Style>            </ControlTemplate.Resources>            <Grid>                <!-- Other controls here -->                <TextBlock Name="LabelText" Style="{StaticResource ButtonLabel}" />            </Grid>        </ControlTemplate>    </StackPanel.Resources>    <Button Width="100" Content="Label Text Here" Template="{StaticResource BarButton}" /></StackPanel>


A property can be qualified simply by prefixing it with the type name. For example, Border.Padding instead of Padding.

However, I'm not sure it makes sense for your scenario. TemplateBindings are used inside a control template.


Yes Definitely,

The {TemplateBinding ...} shortcut is not available in a Setter.

But nobody will stop you using the full verbose version.

Such as: Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Padding}".