如何在TreeView WPF

时间:2015-08-29 13:03:28

标签: c# wpf treeview

我正在使用递归函数填充treeView,如代码所示。对于每个treeviewItem,我使用stackpanel添加复选框。 treeView正确填充,如下图所示。我现在遇到的问题是获取所选节点/复选框(更具体地说,我需要所有选中的" TreeviewItem"对象)。我第一次使用treeview控件,我用google搜索解决方案......但没有成功。

注意:TreeView将有大约6000个节点。因此,除了遍历所有复选框之外,还需要一个解决方案。

enter image description here

 private void button1_Click(object sender, RoutedEventArgs e)
 {
   TreeViewItem ParentNode = new TreeViewItem() { Header = stackedLook("Sub N Node 0"), IsExpanded = true };
   CreatePSTree(RootNode, ParentNode);
   treeView1.items.Add(ParentNode);
 }

 private void CreatePSTree(Product RootNode,  TreeViewItem ParentNode)
 {
      for (int i = 1; i <= RootNode.Products.Count; i++)
       {
        Product NewNode = RootNode.Products.Item(i);
        TreeViewItem NewTreeItem = new TreeViewItem() { Header = stackedLook(NewNode.get_Name()), IsExpanded = false };
        ParentNode.Items.Add(NewTreeItem);                    

        //Recursive calls for each product Node  
        CreatePSTree(NewNode, NewTreeItem);                
      }
  }

 private object stackedLook(string displayText)
   {
     // create stack panel
     StackPanel stack = new StackPanel();
     stack.Orientation = Orientation.Horizontal;

     //Add Checkbox for Node selection
      CheckBox checkBoxForNode = new CheckBox();
      checkBoxForNode.Margin = new System.Windows.Thickness(4);

      // Label displaying the Node name
      Label lbl = new Label();
      lbl.Content = displayText;
      lbl.Margin = new System.Windows.Thickness(-2);

      // Add into stack
      stack.Children.Add(checkBoxForNode);
      stack.Children.Add(lbl);

      return stack;
  }

1 个答案:

答案 0 :(得分:0)

我通过在树视图中添加新节点的所有地方添加事件处理程序以及使用可观察集合来跟踪选择和更改来解决问题

ParentNode.Selected += new RoutedEventHandler(SelectedNodeItem);

void SelectedNodeItem(object sender, RoutedEventArgs e)
 {
    TreeViewItem SelectedTreeViewItem = ((TreeViewItem)e.Source);
 }