【发布时间】:2018-02-22 13:32:12
【问题描述】:
我有一个自定义的控件,它有一个自定义的 DP,这个控件的样式定义了ControlTemplates 的多层:
<ControlTemplate>
<Button>
<Button.Template>
<ControlTemplate>
<!--I want to use the custom DP here-->
<TextBlock Text="{Binding ElementName=myCtrl, Path=SubTitle}"/>
</ControlTemplate>
</Button.Template>
</Button>
</ControlTemplate>
在按钮的控件模板中我想使用自定义DPSubTitle,在当前实现中我使用的是控件名称,但这无助于抽象控件样式和可重用性:
不幸的是我不能使用:
Text="{TemplateBinding SubTitle}"
我找到了这个answer:
这很好,但只有上一级才有用,即它可以在按钮中使用 - 基本控件模板的直接子级,我这样做是为了解决这个问题:
<ControlTemplate>
<Button Tag="{Binding SubTitle, RelativeSource={RelativeSource TemplatedParent}}">
<Button.Template>
<ControlTemplate>
<!--I want to use the custom DP here-->
<TextBlock Text="{TemplateBinding Tag}"/>
</ControlTemplate>
</Button.Template>
</Button>
</ControlTemplate>
但它效率不高,并且不能处理多个 DP。 那么有没有更有效的方法在其孙子中使用基本控件的自定义 DP。
我将借此机会寻求资源,详细解释 Binding 表达式的整个主题:TemplateBinding、RelativeSource 等以及此类属性的奇怪使用(这是 Binding 主题的一部分吗? ):
Storyboard.TargetProperty="(Panel.Background).
(GradientBrush.GradientStops)[1].(GradientStop.Color)"
【问题讨论】:
-
第二个问题见PropertyPath XAML Syntax。