Search code examples
wpfwpf-controlstemplatebinding

How to do a proper Template binding?


I seem to have become a bit rusty on template bindings, I just can't get this to work. Do you see what's wrong?

I have a custom control like this:

public class TextPropertyRow : HeaderedContentControl
{
}

With a style and control template like this:

<Style TargetType="{x:Type Framework:TextPropertyRow}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Framework:TextPropertyRow}">
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="20" />
            <ColumnDefinition Width="*" />
          </Grid.ColumnDefinitions>
          <ContentPresenter ContentSource="Header" />
          <TextBox Text="{TemplateBinding Content}" Grid.Column="2" />
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Which I'm using like this:

<Framework:TextPropertyRow Header="Value"
  Content="{Binding PublicStringPropertyOnDataContext}" />

But values entered into the textbox won't get injected into the viewmodel datacontext. Is this not the correct way of doing it?


Solution

  • For cases where the value is going both ways at runtime, you want to do a regular Binding with RelativeSource TemplatedParent

    <TextBox 
        Text="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" 
        Grid.Column="2"
        />