示例:WPF中TreeView自定义TreeNode泛型绑定对象

一、目的:在开发中经常需要绑定TreeView,所以定义了一个泛型的TreeNode<T>用来方便绑定对象和复用

二、实现

cs 复制代码
    public partial class TreeNodeBase<T> : SelectBindable<T>, ITreeNode
    {
        public TreeNodeBase(T t) : base(t)
        {

        }

        private ObservableCollection<TreeNodeBase<T>> _nodes = new ObservableCollection<TreeNodeBase<T>>();

        public ObservableCollection<TreeNodeBase<T>> Nodes
        {
            get { return _nodes; }
            set
            {
                _nodes = value;
                RaisePropertyChanged();
            }
        }
    }

三、环境

VS2022

四、示例

生成测试数据

cs 复制代码
    public class GetTestTreeNodes : MarkupExtension
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var roots = this.GetTreeNodeBases().ToList();
            foreach (var item in roots)
            {
                var n1 = this.GetTreeNodeBases();
                foreach (var item1 in n1)
                {
                    var n2 = this.GetTreeNodeBases();
                    item1.Nodes = n2.ToObservable();
                }
                item.Nodes = n1.ToObservable();
            }
            return roots;
        }
        private IEnumerable<TreeNodeBase<Student>> GetTreeNodeBases()
        {
            int c = Random.Shared.Next(3, 15);
            for (int i = 0; i < c; i++)
            {
                yield return new TreeNodeBase<Student>(Student.Random());
            }

        }
    }

其中TreeNode<T> 的T使用的测试Student,实际开发中可以使用任意需要的类型,这样在不需要额外定义树结构的情况下可以绑定到树节点上

Xaml中如下绑定

XML 复制代码
  <TreeView ItemsSource="{local:GetTestTreeNodes}">
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
                        <TextBlock VerticalAlignment="Center" Text="{Binding Model.Name}" />
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>

显示效果如下

五、需要了解的知识点

TreeView 类 (System.Windows.Controls) | Microsoft Learn

六、源码地址

GitHub - HeBianGu/WPF-ControlDemo: 示例

GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库

GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库

七、了解更多

System.Windows.Controls 命名空间 | Microsoft Learn

https://github.com/HeBianGu

HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频

相关推荐
zizisuo2 小时前
9.1.领域驱动设计
wpf
大道随心2 小时前
【wpf】10 C#树形控件高效实现:递归构建与路径查找优化详解
开发语言·c#·wpf
离歌漠5 小时前
WPF内嵌其他进程的窗口
c#·wpf
沉到海底去吧Go15 小时前
【身份证识别表格】批量识别身份证扫描件或照片保存为Excel表格,怎么大批量将身份证图片转为excel表格?基于WPF和腾讯OCR的识别方案
ocr·wpf·excel·身份证识别表格·批量扫描件身份证转表格·图片识别表格·图片识别excel表格
csdn_aspnet18 小时前
WPF 性能 UI 虚拟化 软件开发人员的思考
ui·wpf
冰茶_18 小时前
WPF之绑定模式深入
学习·microsoft·微软·c#·wpf·绑定模式
Vae_Mars20 小时前
WPF中如何自定义控件
wpf
冰茶_1 天前
WPF之集合绑定深入
microsoft·微软·c#·wpf·mvvm·数据绑定·布局系统
凌霜残雪1 天前
WPF 3D图形编程核心技术解析
3d·wpf
△曉風殘月〆1 天前
WPF MVVM入门系列教程(五、命令和用户输入)
wpf·mvvm