如何在ContentControl的DataTemplate中绑定数据

29

我有以下简化示例:

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

我在一个单独的ResourceDictionary文件中设置了我的DataTemplate。

我在MainWindow的构造函数中设置了我的DataContext,并通过显示名字来验证它,方法如下:<ContentControl Grid.Row="1" Content="{Binding FirstName}"/>

在另一种情况下,在使用带有ListBox的DataTemplate时,我以与DataTemplate中完全相同的方式进行绑定,并且它可以正常工作。

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

我做错了什么?我的DataTemplate中的绑定应该是什么样子的?

1个回答

70
您需要绑定ContentControlContent属性。
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource PersonTemplate}" />

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

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


1
你有这方面的文档链接吗?它完全解决了我的问题,但我想知道还有没有其他需要注意的地方。 - Mike Cheel
此链接将带您转到Content控件的ContentTemplate属性,我们可以看到ContentTemplate获取或设置用于显示内容的数据模板。https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.contentcontrol.contenttemplate?view=netframework-4.8。根据https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.contentcontrol.content?view=netframework-4.8,内容可以是任何对象。 - Craig Moore

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