【问题标题】:How to do a proper Template binding?如何进行正确的模板绑定?
【发布时间】:2016-08-24 14:29:09
【问题描述】:

我似乎对模板绑定有点生疏了,我就是无法让它工作。你看出什么问题了吗?

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

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

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

【问题讨论】:

  • TemplateBinding 不能是 TwoWay。

标签: wpf wpf-controls templatebinding


【解决方案1】:

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

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

【讨论】:

  • 天哪,忘了。我喜欢 XAML 但 WPF 很烦人 =)
  • @AndreasZita 是的,那一个每周或每两周都会找我。
猜你喜欢
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
相关资源
最近更新 更多