Question

I have a TreeView in my WPF application. The user can create categories in this TreeView. Now I want to add an Item to the selected item of the Treeview. How do I add a childItem to the selected item in a Treeiew?

The following code doesn't work, how can I go about fixing this?

The current code I have:

if (treeViewCategories.SelectedItem != null)
{
    //Unable to cast the SelectedItem to a TreeViewItem('System.String' to 'System.Windows.constrol.TreeViewItem)
    TreeViewItem selectedItem = (TreeViewItem)treeViewCategories.SelectedItem;
    selectedItem.Items.Add(pictureList[counter]);
}
Was it helpful?

Solution

TreeView in WPF has a property called SelectedItem.

TreeViewItem selectedTVI = (TreeViewItem)myTreeView.SelectedItem;
selectedTVI.Items.Add(newChild);

You should read the documentation. SelectedValue is the "value of the property that is the specified by SelectedValuePath for the SelectedItem", not the actual SelectedItem which I've shown above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top