Wpf 如何绑定到ContentControl的Datatemplate中的数据

Wpf 如何绑定到ContentControl的Datatemplate中的数据,wpf,data-binding,datatemplate,resourcedictionary,contentcontrol,Wpf,Data Binding,Datatemplate,Resourcedictionary,Contentcontrol,我有以下简化的例子: <Window x:Class="TemplateBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350

我有以下简化的例子:

    <Window x:Class="TemplateBinding.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary
                            Source="pack://application:,,,/TemplateBinding;component/PersonTemplate.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Window.Resources>
        <Grid>
            <ContentControl ContentTemplate="{StaticResource PersonTemplate}" />
        </Grid>
    </Window>

与:


作为单独的ResourceDictionary文件中的数据模板

我在主窗口的Construcor中设置了DataContext,并通过如下方式显示第一个名称对其进行了验证:

在另一个场景中,当我使用带有
ListBox的DataTemplate时,我在DataTemplate中以完全相同的方式进行绑定,并且它可以正常工作

我知道DataTemplate除了绑定之外还能工作,因为它正确地显示了大小和背景颜色


我做错了什么?“我的数据模板”中的绑定外观如何?

您需要绑定
ContentControl的
Content
属性

<ContentControl Content="{Binding}" ContentTemplate="{StaticResource PersonTemplate}" />

这将ContentControl的DataContext设置为该控件的内容


仅设置
ContentTemplate
属性是不够的。ContentControl不会隐式地将其DataContext用作内容。

您是否有指向此控件上文档的链接?它完全解决了我的问题,但我很好奇是否还有其他问题。此链接将带您到内容控件的ContentTemplate属性,在这里我们可以看到ContentTemplate获取或设置用于显示内容的数据模板。内容可以是符合以下条件的任何对象:
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource PersonTemplate}" />