WPF 创建模板并绑定到列表项属性中的对象



我的数据结构如下所示:

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 中的列表视图,并且我想为汽车和驱动程序创建数据模板。我的用户控件如下所示:

<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}"/>

问题是列表视图不显示汽车驱动程序的信息。我怀疑我的台词

<UserControl DataContext="{Binding CarDriver}"/>

不正确,但我不确定要放什么...?

你应该放一个这样的ContentControl

<ContentControl Content="{Binding CarDriver}">

一切都会正常工作。 如果没有 - 尝试将DriverDataTemplate放在DataTemplate之上,以便Car

最新更新