25

的,我有以下简单的例子:如何一个DataTemplate中绑定到数据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> 

有了:

<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的Construcor中设置了我的DataContext,并通过显示如下名字来验证它:<ContentControl Grid.Row="1" Content="{Binding FirstName}"/>

在另一种情况下,我使用DataTemplate和ListBox我在DataTemplate中使用完全相同的方式进行绑定,它只是起作用。

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

我在做什么错?我的DataTemplate中的绑定怎么看?

回答

54

您需要绑定的ContentControl中

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

这个Content,物业将设置ContentControl中的DataContext的作为控制的内容。

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

+1

你有链接到这个文档?它完全解决了我的问题,但很好奇是否还有其他问题。 – 2015-03-19 17:05:16