Template Binding is similar to normal data binding except it optimize only for Template. The properties are binding used in template binding are coming from the control whose template you are changing. This parent control is called as templated parent. Template binding is subset of normal data binding. Template binding doesn't allow value conversion. Template binding allows the control template to pick up the value specified on an element. Using template binding we can create flexible control template instead of fixed or rigid. Specifying Template binding is very simple, need to specify TemplateBinding markup extension and followed by the property name which you wanted to bind with. Let's have a look on below example.
<Window.Resources>
<ControlTemplate x:Key="ButtonTemplate" TargetType="Button">
<Grid Margin="{TemplateBinding Margin}"
Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}">
<Ellipse x:Name="ButtonEllipse"
Height="100" Width="100"
Fill="LightBlue">
</Ellipse>
<ContentPresenter Content="{TemplateBinding Content}"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Content="Click Me!"
Margin="10" Width="150"
Height="150"
Template="{StaticResource ButtonTemplate}"/>
</Grid>
As demonstrated template binding in above example, grid’s Margin, Height and Width properties are bound using template binding. It means specified Height, Width and Margin property on button will automatically applies to button template. If don’t specified those properties it will automatically take default value of property. Content presenter’s content property is also bound with Button’s content property using Template Binding.
See also -
thanks!
ReplyDeleteVery well explained !!
ReplyDeletethere is a trick to do value conversion:
ReplyDeletehttp://social.msdn.microsoft.com/Forums/en-US/silverlightcontrols/thread/8bded46c-8445-4c55-9c01-83868763f56b/