如何正确进行模板绑定?

时间:2016-08-24 14:29:10

标签: wpf wpf-controls templatebinding

我似乎在模板绑定上变得有点生疏,我只是不能让它工作。你看到了什么错了吗?

我有这样的自定义控件:

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}" />

但是输入文本框的值不会被注入viewmodel datacontext。这不是正确的做法吗?

1 个答案:

答案 0 :(得分:0)

对于值在运行时双向进行的情况,您希望使用RelativeSource TemplatedParent进行常规绑定

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