用于将混合数据添加到树视图的分层数据模板
本文关键字:数据 分层 视图 混合 添加 用于 | 更新日期: 2023-09-27 18:30:31
嗨,我有一个树视图来显示一些分层数据。我的课程如下
public class Response
{
public string UserId { get; set; }
public CaseItems Cases { get; set; }
}
public class CaseItem
{
public int ID { get; set; }
public string Name { get; set; }
public CaseFolders Folders { get; set; }
}
public class CaseFolder
{
public int FolderID { get; set; }
public string FolderName { get; set; }
public CaseItem Case { get; set; }
public CaseFolders Folders { get; set; }
}
public class CaseItems : List<CaseItem> { };
public class CaseFolders : List<CaseFolder> { };
public class Responses : List<Response> { };
我使用这些类创建了一些测试数据。
Responses ResponseList = new Responses();
Response response = new Response();
response.Cases = new CaseItems();
response.UserId = "USER 0001";
ResponseList.Add(response);
CaseItem Case = new CaseItem();
Case.Folders = new CaseFolders();
Case.Name = "CASE0001";
Case.ID = 1;
response.Cases.Add(Case);
CaseFolder MainFolder = new CaseFolder();
MainFolder.FolderID = 1;
MainFolder.FolderName = "Case Folder";
MainFolder.Folders = new CaseFolders();
MainFolder.Case = Case;
Case.Folders.Add(MainFolder);
CaseFolder SubFolder = new CaseFolder();
SubFolder.FolderID = 2;
SubFolder.FolderName = "Sub Folder";
SubFolder.Case = Case;
MainFolder.Folders.Add(SubFolder);
Response AnotherResponse = new Response();
AnotherResponse.Cases = new CaseItems();
AnotherResponse.Cases.Add(Case);
AnotherResponse.UserId = "USER 0002";
ResponseList.Add(AnotherResponse);
tvTest.DataContext = ResponseList;
XAML 如下所示
<TreeView Name="tvTest"
ItemsSource="{Binding}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Response}"
ItemsSource="{Binding}">
<Label Content="{Binding UserId}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:CaseItem}"
ItemsSource="{Binding Cases}">
<Label Content="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:CaseFolder}"
ItemsSource="{Binding ????}">
<Label Content="{Binding Path=FolderName}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
问题是我无法将数据显示到最后一个子文件夹级别。我在 wpf 中看到了很多问题,但是,它们中的大多数在集合或相同类型的嵌套集合中具有相同的类。
我可能无法更改类以返回复合集合,因为这是我从数据层接收数据的方式。
我正在查看这样的结构
User0001
Case0001
Main Folder
Sub Folder
sub...etc...
User0002
etc....
在 xaml 之上,只显示来自 Resonse 类的 UserId。
您必须更新模板,如下所示:
<TreeView Name="tvTest"
ItemsSource="{Binding}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Response}"
ItemsSource="{Binding Cases}">
<Label Content="{Binding UserId}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:CaseItem}"
ItemsSource="{Binding Folders}">
<Label Content="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:CaseFolder}"
ItemsSource="{Binding Folders}">
<Label Content="{Binding Path=FolderName}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
谢谢