将数据模板绑定到ContentControl的Content

3
如何在DataTemplate中将文本框的文本属性绑定到ContentControl的内容属性?(不使用ElementName进行绑定)
以下是我的代码(但它无法正常工作):
<Window.Resources>
    <DataTemplate x:Key="Temp">
       <TextBox TextWrapping="Wrap" Text="{TemplateBinding Content}" Height="20" Width="Auto"/>           
    </DataTemplate>
</Window.Resources>
<Grid>
    <ContentControl  ContentTemplate="{DynamicResource Temp}" Content="1"/>           
</Grid>
1个回答

5
使用相对源绑定:
Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Content}"

编辑:提醒一下,就绑定目标而言,这与{Binding}是等价的,因为在ContentTemplate中的DataContext就是Content

然而直接绑定DataContext不会向源DataContext传播,因此使用此绑定(或双向兼容变体{Binding .})时,ContentControlContent将不会更改,这点需要注意。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接