【问题标题】:How to Bind To Data within a Datatemplate of a ContentControl如何绑定到 ContentControl 的数据模板中的数据
【发布时间】:2013-03-13 15:11:50
【问题描述】:

我有以下简化示例:

    <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 并通过仅显示这样的名字来验证它:&lt;ContentControl Grid.Row="1" Content="{Binding FirstName}"/&gt;

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

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

我做错了什么?我的 DataTemplate 中的 Binding 看起来如何?

【问题讨论】:

    标签: wpf data-binding datatemplate resourcedictionary contentcontrol


    【解决方案1】:

    需要绑定ContentControlContent属性

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

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

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

    【讨论】:

    猜你喜欢
    • 2011-09-07
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2011-12-16
    • 2013-10-10
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多