如何进行正确的模板绑定?

How to do a proper Template binding?

我似乎对模板绑定有点生疏了,我就是无法让它工作。看到哪里不对了吗?

我有一个这样的自定义控件:

public class TextPropertyRow : HeaderedContentControl
{
}

使用这样的样式和控件模板:

<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>

我是这样使用的:

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

但是输入到文本框中的值不会被注入到视图模型数据上下文中。这不是正确的做法吗?

对于值在运行时双向变化的情况,您希望使用 RelativeSource TemplatedParent

进行常规绑定
<TextBox 
    Text="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" 
    Grid.Column="2"
    />