Binding datatemplate to ContentControl's Content

做~自己de王妃 提交于 2019-12-07 12:13:00

问题


How to bind textbox text property, within datatemplate, to ContentControl Content property?
(Without bindng via ElementName)

This is my code( that doesn't work):

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


Use a relative source binding:

Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Content}"

Edit: I probably should note that, in terms of what the binding targets, this is equivalent to {Binding}, as the DataContext in the ContentTemplate is the Content.

However binding directly to the DataContext will not propagate back to the source DataContext, hence the Content of the ContentControl would not change when when using this binding (or the two-way compliant variation {Binding .}, which changes absolutely nothing as far as I can tell).



来源:https://stackoverflow.com/questions/6213969/binding-datatemplate-to-contentcontrols-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!