示例: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个人主页-哔哩哔哩视频

相关推荐
somethingGoWay1 天前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay1 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
self_myth2 天前
[特殊字符] 深入理解操作系统核心特性:从并发到分布式,从单核到多核的全面解析
windows·macos·wpf·harmonyos
c#上位机2 天前
wpf之TextBlock
c#·wpf
玉面小君3 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
c#上位机4 天前
wpf之Border
c#·wpf
SunflowerCoder4 天前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans4 天前
WPF中的DataContext以及常见的绑定方式
wpf
没有bug.的程序员5 天前
Redis 数据结构全面解析:从底层编码到实战应用
java·数据结构·redis·wpf
somethingGoWay5 天前
wpf 自定义输入ip地址的文本框
wpf