c# - 从列表创建树视图WPF
问题描述
我想TreeView
从List<PhonesFromStudents>
.
我的自定义课程是PhonesFromStudents
public class PhonesFromStudents
{
public string Name { get; set; }
public List<string> Phones { get; set; }
}
XAML 是:
<TreeView x:Name="tv_source" Grid.Row="2" Grid.Column="1" Margin="0,5" HorizontalAlignment="Stretch" ItemsSource="{Binding ListStudents}" Background="White" BorderBrush="{x:Null}">
<TreeView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
MainWindows.cs
internal MainWindow(List<PhonesFromStudents> list)
{
InitializeComponent();
this.ListStudents = list;
this.DataContext = this;
}
示例:2 名学生 Thomas - iPhone8,iPhone6 Lucas - iPhone4s, S8
我想拥有
Thomas
|_____iPhone8
|_____iPhone6
Lucas
|_____iPhone4s
|_____S8
但我从 UI 得到一个空列表。有人能帮我吗?谢谢
解决方案
使用HierarchicalDataTemplate
:
<TreeView x:Name="tv_source" Grid.Row="2" Grid.Column="1" Margin="0,5"
HorizontalAlignment="Stretch" ItemsSource="{Binding ListStudents}" Background="White" BorderBrush="{x:Null}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:PhonesFromStudents}" ItemsSource="{Binding Phones}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
...并确保这ListStudents
是公共财产:
public List<PhonesFromStudents> ListStudents { get; set; }
推荐阅读
- r - 根据列值对构面进行排序
- swift - Swift 命令行工具 -> 使用箭头键和空格键选择
- javascript - 如何同时延迟加载多个组件
- office365 - Office 加载项清单文件通过“npm run validate”但在侧加载到 Office Web 时失败
- json - 在 After Effects 中使用 JSON 设置图层或合成的入口点
- html - BS4 减少移动设备上 2-Up 网格卡之间的填充
- c# - .NET C# 上的无服务器数据库
- c# - ViewModel 复杂对象从视图传递到控制器时返回 null
- c# - 如何从 MainWindow 中的 ViewModel 订阅事件?
- javascript - 如何使用 indexOf() 而不是 includes() 返回布尔值?