一、目的:在开发中经常需要绑定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轻量控件和皮肤库