TemplateBinding – It’s sugar

When re-templating existing controls the TemplateBinding is your friend. It’s a way of getting user specified values for properties of the control and using them in your control template at runtime.

As in the example below we change a Label into a TextBox and use a TemplateBinding to set the Text of the TextBox to whatever the Content is of the Label.

<Label Content="Show me in a Label">
    <ControlTemplate TargetType="Label">
      <TextBox Text="{TemplateBinding Content}" />

However, if you try and bind to the Content of the Label you will notice that the source will never get updated with any changes typed into the TextBox/Label.
This is because TemplateBinding is really just syntactic sugar for the following:

{Binding Content, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}

So, if we want to do two-way TemplateBinding we just need to use the following binding instead of using a TemplateBinding.

{Binding Content, RelativeSource={RelativeSource TemplatedParent}}

One Reply to “TemplateBinding – It’s sugar”

  1. Unable to cast object of type ‘System.Windows.TemplateBindingExpression’ to type ‘System.Windows.Data.BindingBase’.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s