How to bind to control properties from ControlTemplate


Hi guysSmile. Today I will show you how to bind to control properties from ControlTemplate.

Let’s say that we have the following template for button:

<ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="border"> <ContentPresenter x:Name="contentPresenter"/> </Border> </ControlTemplate>

Imagine that you want to set some property for this border using value specified for Button Background property:

<Button Content="Button" Background="Red"/>

You should use TemplateBinding markup extension in this case:

<ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="border" Background="{TemplateBinding Background}"> <ContentPresenter x:Name="contentPresenter"/> </Border> </ControlTemplate>

Sometimes you can’t use TemplateBinding:

<ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="border"> <ContentPresenter x:Name="contentPresenter"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true" > <Setter TargetName="border" Property="Background" Value="{TemplateBinding Background}"/> </Trigger> <Trigger Property="IsMouseOver" Value="false" > <Setter TargetName="border" Property="Background" Value="Blue"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate>

In this case, XamlParseException will be thrown telling, “Expression type is not a valid Style value”. This is due to inability to use TemplateBinding in setters.

Fortunately, you can use normal Binding markup extension in combination with RelativeSource property to achieve desired result:

<ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true" > <Setter TargetName="border" Property="Background" Value="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}"/> </Trigger> <Trigger Property="IsMouseOver" Value="false" > <Setter TargetName="border" Property="Background" Value="Blue"/> </Trigger> </ControlTemplate.Triggers>

As you can see, it is not so difficult to get control properties values using TemplateBinding or Binding markup extensions. Bye Winking smile

Advertisements