1

In WPF treeview control, I need to add a child node to a parent node i select using mousedoubleclick event.

http://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.selecteditem.aspx

I followed the step in the MSDN, but i get invalidCastException when i do this.

TreeViewItem newChild = (TreeViewItem)treeView1.SelectedItem;

How can i solve this?

Thanks

1
  • A better idea would be to bind your TreeView to an object graph, and have lazily loaded collection properties in that graph. Commented Sep 8, 2009 at 23:44

2 Answers 2

2

SelectedItem returns the selected data item, not the visual representing it.

If you need to access the selected TreeViewItem, use the ItemContainerGenerator :

TreeViewItem item = treeView1.ItemContainerGenerator.ContainerFromItem(treeView1.SelectedItem) as TreeViewItem;

Not sure it works for nested items though... you might have to use the ItemContainerGenerator of the parent TreeViewItem, which wouldn't be very convenient

EDIT: just tested, indeed it only works for root nodes...

Anyway, the best way to add a node is to use bindings and HierarchicalDataTemplates. You just need to add the object to the data source, and the corresponding TreeViewItem will be added automatically (provided the containing collection implements INotifyCollectionChanged...)

Sign up to request clarification or add additional context in comments.

Comments

1

What type of Items do you Add() to the Tree? The same type will be returned.
If it is mixed, use

TreeViewItem newChild = treeView1.SelectedItem as TreeViewItem;
if (newChild != null) { ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.