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

相关推荐
mrchip11 小时前
Simple WPF: WPF 实现按钮的长按,短按功能
c#·wpf·.net core
mrchip1 天前
Simple WPF: WPF 自定义按钮外形
c#·wpf
martian6651 天前
学懂C#编程:WPF应用开发系列——WPF之ComboBox控件的详细用法
开发语言·c#·wpf·控件·combobox
K哥爬虫1 天前
【0基础学爬虫】爬虫框架之 feapder 的使用
爬虫·wpf
云草桑2 天前
WPF UI 界面布局 魔术棒 文字笔记识别 技能提升 布局功能扩展与自定义 继承Panel的对象,测量与排列 系列七
ui·wpf·设计·布局·版式设计
罗迪尼亚的熔岩2 天前
使用附加属性 实现wpf中的passwordBox 的明文/密文密码切换
wpf·状态模式
小海聊工控上位机2 天前
WPF资源的使用
c#·wpf
无熵~2 天前
C#/WPF 自制白板工具
开发语言·c#·wpf
mingupup2 天前
WPF在.NET9中的重大更新:Windows 11 主题
windows·.net·wpf
小海聊工控上位机3 天前
WPF自定义模板--TreeView 实现菜单连接线
wpf