定義
TemplateBinding是為了某個特定場景優化出來的數據綁定版本--需要把ControlTemplate里面的某個Property綁定到應用該ControlTemplate的控件的對應Property上。
中文表達比較拗口,MSDN的原文“Links the value of a property in a control template to be the value of a property on the templated control.”
用法
在屬性賦值中直接的用法:
<object property="{TemplateBinding targetProperty}" .../>
在模板或樣式中用Setter屬性的用法:
<Setter Property="propertyName" Value="{TemplateBinding targetProperty}" .../>
區別
1. Binding比TemplateBinding更加靈活強大,但是開銷也更大。TemplateBinding在使用場景有限制,但是效率較高。Template非常類似{Binding RelativeSource={RelativeSource TemplatedParent}}構造的Binding。
2. TemplateBinding同樣允許我們定義Converter和ConverterParameter,在一定程度上加強了TemplateBinding的應用功能和范圍.
3. 最重要的區別:TemplateBinding僅僅支持單向的數據綁定,從應用Template的控件到Template(from templated control to template)。如果我們需要反向或者雙向的綁定,唯一的選擇就是應用Binding和RelativeSource。
結論
討論了區別,最終我們需要的是一個結論,到底什么時候用哪種Binding?
如果我們需要一個單向的綁定,使數據從應用template的控件(templated parent)到template,我們就該使用高效而簡單的TemplateBinding,其他情況下都使用Binding。