[WPF系列-高级TemplateBinding vs RelativeSource TemplatedParent]
What is the difference between these 2 bindings:
<ControlTemplate TargetType="{x:Type Button}"> <Border BorderBrush="{TemplateBinding Property=Background}"> <ContentPresenter /> </Border> </ControlTemplate>
and
<ControlTemplate TargetType="{x:Type Button}"> <Border BorderBrush="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}"> <ContentPresenter /> </Border> </ControlTemplate>
TemplateBinding - More limiting than using regular Binding
- More efficient than a Binding but it has less functionality
- Only works inside a ControlTemplate's visual tree
- Doesn't work with properties on Freezables
- Doesn't work within a ControlTemplate's Trigger
- Provides a shortcut in setting properties(not as verbose),e.g. {TemplateBinding targetProperty}
Regular Binding - Does not have above limitations of TemplateBinding
- Respects Parent Properties
- Resets Target Values to clear out any explicitly set values
- Example: <Ellipse Fill="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}"/>
One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).
TempleteBinding is a shorthand for Binding with TemplatedParent but it does not expose all the capabilities of the Binding class, for example you can't control Binding.Mode from TempleteBinding.
参考
WPF TemplateBinding vs RelativeSource TemplatedParent
作者:旭东
出处:http://www.cnblogs.com/HQFZ
关于作者:专注于微软平台项目架构、管理和企业解决方案。现主要从事WinForm、ASP.NET、WPF、WCF、等方面的项目开发、架构、管理。如有问题或建议,请不吝指教!
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以联系我,非常感谢。
如果您该文觉得不错或者对你有帮助,请点下推荐,让更多的朋友看到,谢谢!