TemplateBinding is used for binding to the element properties within the template definition. In your example, you could have written:
<Border Padding="{Binding Padding}" ...>
...meaning to bind the border's padding property to the padding property of... what? You'd like to say, "padding property of the control that this template is being used for." You can't give it a name because you don't know the x:Name of the control at this time (even if you did, it wouldn't work because it's in a different namescope). However, you can do this by defining a relative source
<Border Padding="{Binding Padding, RelativeSource={RelativeSource TemplatedParent}" ...>
or use TemplateBinding, which is a shortcut(*) for above
<Border Padding="{TemplateBinding Padding}" ...>
(*) In addition to being less verbose in these templating scenarios, TemplateBinding has a couple of differences compared to a regular binding:
- It is evaluated at compile-time. (if, for example, Padding property didn't exist, you would get a compile error. But if you were to use a binding with TemplatedParent, you would only see the error at runtime.)
- It is always a one-way binding.
- It requires that both the source and target properties are dependency properties.
- It has much less functionality (no StringFormat, Delay, IsAsync, etc.. see the properties of Binding vs TemplateBindingExtention).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…