How to draw binary tree view using WPF?

核能气质少年 提交于 2019-12-05 12:42:17

Each of your tree nodes need to have a collection of children. If you want to limit it to a binary tree then you can limit your collection of children to a max capacity of 2 items.

I would recommend this tutorial as it will also show you how to achieve this with MVVM.

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

EDIT:

Since you have updated your post and it seems like you are looking for something different, I think you would be better off using a 3rd party solution instead of implementing your own.

Try looking at these solutions -

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

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

So, I restructured your code according to my above comment. The BinaryTreeData now have a SubItems List. You'll have to adjust the namespace in XAML / local:BinaryTreeData and it should work.. Cheers !

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<BinaryTreeData> _subitems = new List<BinaryTreeData>();

    public List<BinaryTreeData> Subitems
    {
      get { return _subitems; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void onChange(string propertyName)
    {
      if (PropertyChanged != null)
      {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }
  }

XAML:

<TreeView x:Name="myTreeView">
  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate DataType="{x:Type local:BinaryTreeData}" ItemsSource="{Binding Subitems}">
      <TextBlock  Text="{Binding Path=ownID}" />
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>

CodeBehind:

public MainWindow()
{
  InitializeComponent();

  List<BinaryTreeData> myBinaryData = new List<BinaryTreeData>();

  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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!