TreeView获取选定的节点问题

时间:2013-10-30 18:00:22

标签: wpf treeview treeviewitem

尝试获取在树视图中选择的父节点和子节点标头,但是我收到错误,它无法将字符串转换为TreeViewItem。

private void tvSQLTasks_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        //error is here
        TreeViewItem child = (TreeViewItem)tvSQLTasks.SelectedItem;

        if (child.Parent is TreeViewItem)
        {
            TreeViewItem parent = (TreeViewItem)child.Parent;

            SQLTask _task = SQLTasks.Where(t => t._rootNode.Equals(parent.Header.ToString()) && t._childNode.Equals(child.Header.ToString())).FirstOrDefault();

            if (_task != null)
            {
                txtTaskDescription.Text = _task._taskDescription;
            }
        }
    }

以下是我添加节点的方法

      private void AddRootNode(string _nodeName)
    {
        tvSQLTasks.Items.Add(new TreeViewItem() { Header = _nodeName });
    }

    private void AddChildNode(string _rootNode, string _childeNode)
    {
        foreach (TreeViewItem node in tvSQLTasks.Items)
        {
            if (node.Header.Equals(_rootNode))
            {
                (node as TreeViewItem).Items.Add(_childeNode);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

这似乎是问题界限:

 (node as TreeViewItem).Items.Add(_childeNode);

尝试将其更改为:

 node.Items.Add(new TreeViewItem() { Header = _childeNode});