我的数据结构如下所示:
public class MyDataContext
{
public ObservableCollection<Car> CarList {set; get;}
}
public class Car
{
public Driver CarDriver {set; get;} // implements INotifyPropertyChanged (not shown here to keep it short)
public string Color {set; get;} // implements INotifyPropertyChanged (not shown here to keep it short)
public string Brand {set; get;} // implements INotifyPropertyChanged (not shown here to keep it short)
}
public class Driver
{
public string Name {set; get;}
public string Nationality {set; get;}
}
我将 CarList 绑定到我的 XAML 中的 ListView,并且我想为 Car 和 Driver 创建 DataTemplates。我的用户控件看起来像这样:
<UserControl.Resources>
<DataTemplate DataType="{x:Type local:Car}>
<StackPanel>
<UserControl DataContext="{Binding CarDriver}"/>
<TextBlock Text="{Binding Color}"/>
<TextBlock Text="{Binding Brand}"/>
</StackPanel>
</DataTemplate>
<DataDataTemplate DataType="{x:Type local:Driver}>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Nationality}"/>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<ListView ItemsSource="{Binding CarList}"/>
问题是 ListView 没有显示 CarDriver 的信息。我怀疑我的线路
<UserControl DataContext="{Binding CarDriver}"/>
是不正确的,但我不知道该放什么...?