Can my WPF Style Setter use a TemplateBinding?

跟風遠走 提交于 2019-11-29 05:32:58

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>
Kent Boogaart

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!