UWP 将 ListView 的项目绑定为 UserControl DataTemplate

UWP bind a ListView's item as UserControl DataTemplate

我尝试实现一个 Master/detail 视图,我试图了解如何将 selected 项绑定到具有两个 DataTemplate 的 UserControl 中。

我有两种模型(我称他们为老师和学生)

我的视图模型:

public class Page_ProfilVM : NotificationBase
{
    public ObservableCollection <AbstractInfosProfilVM> InfosProfil { get; set; }
    private AbstractInfosProfilVM selectedProfil;
    public  AbstractInfosProfilVM SelectedProfil
    {
        get { return selectedProfil; }
        set
        {
            SetProperty(selectedProfil, value, () => selectedProfil = value);
         }   
     }
}

public abstract class AbstractInfosProfilVM : NotificationBase
{
    private string nom;
    public  string Nom
    {
        get { return nom; }
        set { SetProperty(nom, value, () => nom = value); }
    }
}

public class TeacherInfosProfilVM : AbstractInfosProfilVM
{
}
public class StudentInfosProfilVM : AbstractInfosProfilVM
{
}

我正确显示主视图

<!-- ListView -->
<ListView  ItemSource="{x:bind ViewModel.Profils}" 
           SelectionMode="Single" 
           SelectedItem="x:bind ViewModel.SelectedProfil, Mode="TwoWay", Converter={.....}}">

<ListView.ItemTemplate>
    <DataTemplate x:DataType="vm:AbstractProfilVM">
        <!-- Master -->
        <widget:CelProfilMaster CelProfilMasterName={x:Bind Name} CelProfilMasterAge={x:Bind Age} ... />
    </DataTemplate>
</ListView.ItemTemplate>

而且我在详细视图(具有依赖属性的用户控件)上正确显示了 selected 项目的详细信息。但现在我需要 select 正确的 dataTempalte 来显示教师的属性和学生的属性。但它不起作用。

<!-- Details-->
<widget:CelluleProfilDetails x:Name = "DetailContent" 
                             CelluleProfilDetailsNom = "{x:Bind ViewModel.SelectedProfil.Nom,Mode=TwoWay,Converter={StaticResource GenericConverter}}"
                             CelluleProfilDetailsPrenom = "{x:Bind ViewModel.SelectedProfil.Prenom, Mode=TwoWay,Converter={StaticResource GenericConverter}}" >

<widget:CelluleProfilDetails.CelluleProfilDetailsContent>
    <ContentPresenter Content="{x:Bind ViewModel.SelectedProfil,Mode=OneWay}">

    <ContentPresenter.Resources>
        <DataTemplate x:DataType="viewModels:TeacherInfosProfilVM" x:Name="T1" >
            <TextBlock Text="{x:Bind Nom}"/>
        </DataTemplate>
        <DataTemplate x:DataType="viewModels:StudentInfosProfilVM" x:Name="T2" >
            <TextBlock Text="{x:Bind Nom}"/>
        </DataTemplate>
    </ContentPresenter.Resources>

    </ContentPresenter>                        
</widget:CelluleProfilDetails.CelluleProfilDetailsContent>

</widget:CelluleProfilDetails>

我尝试显示 Teacher/Student 的名称,但它只显示视图模型的名称。 如何将教师属性和学生属性正确显示为"CelluleProfilDetails.CelluleProfilDetailsContent"?

如果您实际上正在寻找允许您根据数据类型将两个不同的数据模板加载到您的视图模型的数据绑定概念,那么您绝对应该观看下面的视频。

我在我的一个应用程序中实现了相同的功能,我不想在此处 post 任何代码,因为它只是另一种复制粘贴解决方案。

See This Video

如果您对 DataTemplateSelector 的解释有任何疑问,请告诉我。