WPF TemplateBinding vs RelativeSource TemplatedParent
这两种绑定之间的差异是什么WPF TemplateBinding vs RelativeSource TemplatedParent,wpf,relativesource,templatebinding,Wpf,Relativesource,Templatebinding,这两种绑定之间的差异是什么 <ControlTemplate TargetType="{x:Type Button}"> <Border BorderBrush="{TemplateBinding Property=Background}"> <ContentPresenter /> </Border> </ControlTemplate> 及 ?它们的使用方式相似,但有一些不同。 以下是Templat
<ControlTemplate TargetType="{x:Type Button}">
<Border BorderBrush="{TemplateBinding Property=Background}">
<ContentPresenter />
</Border>
</ControlTemplate>
及
?它们的使用方式相似,但有一些不同。 以下是TemplateBinding文档的链接:
TemplateBinding是使用TemplatedParent进行绑定的简写,但它并不公开绑定类的所有功能,例如,您无法从TemplateBinding控制Binding.Mode。TemplateBinding不是一回事。MSDN文档通常是由那些必须对单音节SDE进行软件功能测试的人编写的,因此这些细微差别并不完全正确 TemplateBindings在编译时根据控件模板中指定的类型进行评估。这允许更快地实例化已编译模板。只需在templatebinding中摸索名称,您将看到编译器将标记它 绑定标记在运行时解析。虽然执行速度较慢,但绑定将解析在模板声明的类型上不可见的属性名称。更慢一点,我将指出它是相对的,因为绑定操作占用应用程序很少的cpu。如果您正在高速地使用控制模板,您可能会注意到它
作为一种实践,在可能的情况下使用TemplateBinding,但不要害怕绑定。我认为TemplateBinding不支持Freezable类型(包括笔刷对象)。避开这个问题。可以使用TemplatedParent的还有一件事——TemplateBinding不允许值转换。例如,它们不允许您传递转换器,也不允许自动将int转换为string(这对于绑定来说是正常的)。-比使用常规绑定更具限制性
- 比绑定更高效,但功能更少
- 仅适用于ControlTemplate的可视树
- 不适用于Freezable上的属性
- 在ControlTemplate的触发器中不起作用
- 提供设置属性的快捷方式(不是详细的),例如{TemplateBinding targetProperty}
- 尊重父属性
- 重置目标值以清除任何显式设置的值
- 例如:
<ControlTemplate TargetType="{x:Type Button}">
<Border BorderBrush="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}">
<ContentPresenter />
</Border>
</ControlTemplate>