C# WPF - 将子节点添加到树视图中的选定节点 [英] C# WPF - Adding a child node to a selected node in treeview

查看:25
本文介绍了C# WPF - 将子节点添加到树视图中的选定节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WPF 树视图控件中,我需要将子节点添加到我使用 mousedoubleclick 事件选择的父节点.

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

我按照 MSDN 中的步骤操作,但是在执行此操作时出现 invalidCastException.

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

TreeViewItem newChild =(TreeViewItem)treeView1.SelectedItem;

TreeViewItem newChild = (TreeViewItem)treeView1.SelectedItem;

我该如何解决这个问题?

How can i solve this?

谢谢

推荐答案

SelectedItem 返回选定的数据项,而不是表示它的视觉对象.

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

如果您需要访问选定的TreeViewItem,请使用 ItemContainerGenerator :

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

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

不确定它是否适用于嵌套项目...您可能必须使用父 TreeViewItem 的 ItemContainerGenerator,这不是很方便

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

刚刚测试过,确实只适用于根节点...

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

无论如何,添加节点的最佳方式是使用绑定和HierarchicalDataTemplate.只需将对象添加到数据源中,就会自动添加对应的TreeViewItem(前提是包含的集合实现了INotifyCollectionChanged...)

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...)

这篇关于C# WPF - 将子节点添加到树视图中的选定节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆