Monday, August 26, 2013

What is TemplateBinding in WPF – short example.

TemplateBinding has to do with the ControlTemplate, in brief it is a way to inject property into the template from the template user. You've probably heard about the lookless nature of WPF controls which means that unlike behavior (which is fixed), the appearance of a control can be replaced entirely by supplying a new ControlTemplate.

Consider the following template for a ToggleButton. This is simply a polygon with a stroke and an orange fill.
<Window x:Class="TemplateBindingTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
  <Style x:Key="PolygonToggleButtonStyle" TargetType="ToggleButton">
    <Style.Setters>
      <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
            <Polygon Name="CenterPolygon" Points="90,10 50, 50, 10,10" 
            Fill="Orange" Stroke="Gray" StrokeThickness="0"/>
            <ControlTemplate.Triggers>
              <Trigger Property="IsChecked" Value="True">
                <Setter TargetName="CenterPolygon" Property="StrokeThickness" Value="3"/>
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style.Setters>
  </Style>
</Grid.Resources>

<StackPanel Width="100">
  <ToggleButton Background="Pink" Style="{StaticResource PolygonToggleButtonStyle}"/>
</StackPanel>
</Grid>
</Window>

See that in spite of setting the Background property to Pink, the button is still orange since this is the value hardcoded in template.


Because we provided our own ControlTemplate we must explicitly say how the template should use parameters provided by the control's user. This is a situation when TemplateBinding becomes handy. We will instruct the Fill property to capture the value of Background property in the following way.

<Polygon Name="CenterPolygon" Points="90,10 50, 50, 10,10" 
Fill="{TemplateBinding Background}" Stroke="Gray" StrokeThickness="0"/>

1 comment:

  1. short and crisp example helped me to understand the concept clearly....thumbs up

    ReplyDelete