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}
常规-没有模板绑定的上述限制

  • 尊重父属性
  • 重置目标值以清除任何显式设置的值
  • 例如:

所以要记住的主要问题是:编译时与运行时。如果在运行时尝试更改TemplateBinding,它将无法工作。对吗?还要注意,使用绑定而不是TemplateBinding可能会影响到您在设计时看到的内容。在某些配置中,使用{Binding RelativeSource…}绑定的属性不会出现在设计器中(尽管它们在运行时仍会显示),但如果切换到使用{TemplateBinding…}这些属性是在设计时计算的。我要补充一点,以防它对未来的访问者有所帮助,因为TemplateBinding是在编译时计算的,所以不能使用TemplateBinding绑定到用户定义的附加属性。对于用户定义的附加属性,您必须使用“{Binding RelativeSource={RelativeSource TemplatedParent}…””感谢Miroslav,这就是我遇到的问题,切换到使用TemplatedParent解决了问题。如果需要双向绑定,您必须使用第二个选项
<ControlTemplate TargetType="{x:Type Button}">
   <Border BorderBrush="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}">
      <ContentPresenter />
   </Border>
</ControlTemplate>