如何使用WPF绘制二叉树视图?

我想像这样画出它:

在此处输入图像描述

我可以在控制台上绘制二叉树。 我想用WPF绘制它。 这是我为控制台编写的代码。

class Program { static void Main(string[] args) { List myBinaryData = new List(); myBinaryData.Add(new BinaryTreeData{ownID=1}); myBinaryData.Add(new BinaryTreeData { parentID=1, ownID = 2 }); myBinaryData.Add(new BinaryTreeData { parentID=1,ownID = 3 }); foreach (var item in myBinaryData) { Console.WriteLine("{0}------{1}", item.parentID, item.ownID); } } } class BinaryTreeData : INotifyPropertyChanged { private int _ownID; private int _parentID; public int ownID { get { return this._ownID; } set { this._ownID = value; this.onChange("ownID"); } } public int parentID { get { return this._parentID; } set { this._parentID = value; this.onChange("parentID"); } } public event PropertyChangedEventHandler PropertyChanged; private void onChange(string propertyName) { if (PropertyChanged!=null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } 

我不明白我该怎么做。

每个树节点都需要有一个子集合。 如果要将其限制为二叉树,则可以将子集合限制为最多2个项目。

我会推荐这个教程,因为它还将向您展示如何使用MVVM实现此目的。

http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx

编辑:

既然你已经更新了你的post,看起来你正在寻找不同的东西,我认为你最好使用第三方解决方案,而不是实现自己的。

试着看看这些解决方案 –

http://www.codeproject.com/KB/WPF/LayeredTreeDraw.aspx

http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx

所以,我根据上面的评论重新构建了代码。 BinaryTreeData现在有一个SubItems List。 你必须调整XAML / local中的命名空间:BinaryTreeData它应该工作..干杯!

BinaryTreeData:

  public class BinaryTreeData : INotifyPropertyChanged { private int _ownID; private int _parentID; public int ownID { get { return this._ownID; } set { this._ownID = value; this.onChange("ownID"); } } private List _subitems = new List(); public List Subitems { get { return _subitems; } } public event PropertyChangedEventHandler PropertyChanged; private void onChange(string propertyName) { if (PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } 

XAML:

        

代码隐藏:

 public MainWindow() { InitializeComponent(); List myBinaryData = new List(); BinaryTreeData parent1 = new BinaryTreeData() { ownID = 1 }; parent1.Subitems.Add(new BinaryTreeData { ownID = 2 }); parent1.Subitems.Add(new BinaryTreeData { ownID = 3 }); BinaryTreeData parent2 = new BinaryTreeData() { ownID = 4 }; parent2.Subitems.Add(new BinaryTreeData { ownID = 5 }); parent2.Subitems.Add(new BinaryTreeData { ownID = 6 }); myBinaryData.Add(parent1); myBinaryData.Add(parent2); myTreeView.ItemsSource = myBinaryData; }