我有以下简化示例:
<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中的绑定应该是什么样子的?