如何获取树视图中的子位置?
我目前有一个简单的树视图,其中包含一个父节点和多个子节点。我想知道是否有办法找到父树中所选节点的位置。
我当前在树视图上有一个操作事件,当用户单击子项时,它会打印出所选子项的字符串值。我尝试过使用:
int val = TreeView.SelectedItemProperty.GlobalIndex;
但它总是返回 0。我在 VB 中看到了一些示例,但我似乎无法在 C# 中得到相同的想法。
I currently have a simple tree view that contains one parent node with multiple child nodes. I was wondering if there is a way to find the location of the selected node in the parent tree.
I currently have an action event on the treeview and when the user clicks on the child it prints out the string value of the selected child. I have tried using:
int val = TreeView.SelectedItemProperty.GlobalIndex;
but it always returns 0. I have seen some examples in VB but I cant seem to get the same idea to work in C#.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须使用 Treeview 的 ItemContainerGenerator 属性。
http://msdn.microsoft.com/en-us /library/system.windows.controls.itemcontainergenerator.aspx
请参阅:ContainerFromIndex 和 IndexFromContainer
请注意,每个 TreeViewItem 也有一个 ItemContainerGenerator(其ItemsControl),因此如果有多个级别,则必须在树中递归搜索。
You have to use the ItemContainerGenerator property of the Treeview.
http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcontainergenerator.aspx
See: ContainerFromIndex and IndexFromContainer
Note that each TreeViewItem also has an ItemContainerGenerator (its an ItemsControl), so you'd have to recursively search down the tree if you have multiple levels.
我认为 wpf 中所有树视图问题(以及大多数 ui 问题)的答案是构建一个 ViewModel。每当您开始爬行可视化树以查找已绑定到的元素时,您都会以困难的方式做事。一旦你开始使用 ItemsContainerGenerator,你就必须开始担心很多你不应该担心的问题。
您正在绑定到层次结构。如果该结构的每个项目都有一个选定的项目属性,并且它绑定到 TreeViewItem 选定的项目,那么您只需在代码中获取选定的项目并从那里执行其他所有操作。看看类似的问题这里。
I think the answer to all your treeview problems (and most ui ones) in wpf is to build a ViewModel. Anytime you start crawling the visual tree to look for elements that you are already binding to, you are doing things the hard way. Once you start using ItemsContainerGenerator you have to start worrying about a whole lot of issues you should not have to.
You are binding to a hierarchical structure. If that structure has a selected item property on each item and it is bound to the TreeViewItem selected item then you can just get the selected item in code and do everything else from there. Have a look at a similiar question here.
所以我没有找到我正在寻找的答案(我可能会让其他人对我的问题感到困惑。通过说位置)。无论如何,我解决这个问题的方法是获取所选子项的字符串值并将其与我的列表进行比较。感谢那些回答的人!
So i didn't find the answer i was looking for (I may of confused others with what my question was. by saying location). Anyways how I solved it was I got the string value of the child selected and compared it to my list. Thanks to those who answered!