Friday, September 23, 2011

Template Binding in WPF

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.

<ControlTemplate x:Key="ButtonTemplate" TargetType="Button">
    <Grid Margin="{TemplateBinding Margin}"
          Height="{TemplateBinding Height}"
          Width="{TemplateBinding Width}">
        <Ellipse x:Name="ButtonEllipse"
                    Height="100" Width="100"
        <ContentPresenter Content="{TemplateBinding Content}"
                    VerticalAlignment="Center" />
<Button Content="Click Me!"
        Margin="10" Width="150"
        Template="{StaticResource ButtonTemplate}"/>

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 - 


  1. there is a trick to do value conversion: