问题
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