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

mar*_*s s 26 data-binding wpf 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" 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>
Run Code Online (Sandbox Code Playgroud)

附:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

        <DataTemplate x:Key="PersonTemplate">
            <Border Width="100" Height="100" Background="RosyBrown">
                <TextBlock Text="{Binding Path=FirstName}" VerticalAlignment="Center" TextAlignment="Center"/>
            </Border>
        </DataTemplate>

    </ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

作为我的DataTemplate在一个单独的ResourceDictionary文件中.

我在我的MainWindow的Construcor中设置了我的DataContext,并通过显示如下的第一个名称来验证它:<ContentControl Grid.Row="1" Content="{Binding FirstName}"/>.

在另一个场景中,我使用DataTemplate与我在DataTemplate中以ListBox完全相同的方式进行绑定,它只是起作用.

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

我究竟做错了什么?我的DataTemplate中的绑定如何看?

Jeh*_*hof 56

您需要绑定ContentContentControl 的-Property

<ContentControl Content="{Binding}" ContentTemplate="{StaticResource PersonTemplate}" />
Run Code Online (Sandbox Code Playgroud)

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

仅设置ContentTemplate属性是不够的.ContentControl不会隐式使用其DataContext作为内容.