How to add to a TreeView directory at runtime

断了今生、忘了曾经 提交于 2020-01-11 12:57:11

问题


I have a TreeView in which I would like to allow the user to add and delete subitems from. In exploring basic functionality I am using a button and a textbox to add this subitem. When the user clicks on the button a new TreeViewItem needs to be created and set as a subitem of my parent TreeView with the text from the textbox set as the subitem's Header.

This is my current code under the button_click event:

//ADD T_ITEM TO PARENT TREEVIEW
private void button1_Click(object sender, RoutedEventArgs e)
{
       TreeViewItem item = new TreeViewItem();
       item.Header = textBox1.Text;

       //Compiler does not recognize "Nodes"
       Parent.Nodes.Add(item);
}

Specifically, the compiler has a problem with Nodes. The main question that I've used to help me makes a lot of sense, but just doesn't work for me. All of the sources I have looked at uses the Nodes command at one time or another with no problem. Do I need to include a reference, or is my code completely off?

--This guide uses System.Windows.Forms; in order to use Nodes, but doesn't seem to help because I am using Windows Presentation Foundation.

Please show me how to get my code working in the right direction.

Thank you.


回答1:


I did some more research and found the equivalent method for adding child TreeViewItems to parent TreeViewItems in WPF.

This is the change I made to my code:

//ADD T_ITEM TO PARENT TREEVIEW
private void button1_Click(object sender, RoutedEventArgs e)
{
      TreeViewItem item = new TreeViewItem();
      item.Header = textBox1.Text;

      Parent.Items.Add(item);
}


来源:https://stackoverflow.com/questions/17866294/how-to-add-to-a-treeview-directory-at-runtime

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