-
Aug 28th, 2014, 01:31 PM
#1
Thread Starter
Hyperactive Member
How to find parent of selected item in TreeView?
Okay, using Windows 7 with VS2012 and .NET 4.5 in a WPF application, I have a multi-level treeview that looks like this:
The TreeView is bound to an observable collection of the codes. What I want SHOULD be simple, but it's not turning out to be so. Let's assume that the user clicks on the "6010F-8P" item... how can I find the parent item ("6015F-00")? The data can be up to four levels deep, and I need to be able to backtrack up the entire chain to find not only the root item, but also each parent along the way.
I have searched and searched, but can't find any way to do this. Is there any way for the TreeView control to do find the parent item of a selected item?
Thanks in advance...
-
Aug 28th, 2014, 01:40 PM
#2
Re: How to find parent of selected item in TreeView?
To get the item's parent is simple it's like this:
Code:
Dim parent As TreeNode = currentNode.Parent
However if you're wanting to get every parent up the chain, it'd go something like this(I'm free-typing it by the way so there may be a typo):
Code:
Private Function GetParents(ByVal currentNode As TreeNode) As TreeNode()
'Create a new instance of a List(Of TreeNode)
Dim chain As List(Of TreeNode) = New List(Of TreeNode)
'Declare a variable to hold the parent node
Dim nextNode As TreeNode = currentNode.Parent
'Add the initial parent to the List(Of Node)
chain.Add(nextNode)
Do
'The next node will be the current node that we are on's parent
nextNode = nextNode.Parent
'If the next node is something then add it to the List(Of Node)
If nextNode IsNot Nothing Then
chain.Add(nextNode)
End If
'Exit the loop if the next node is nothing
Loop Until IsNothing(nextNode)
'Return the array of nodes
Return chain.ToArray()
End Function
With that function, the first item in the array will be the current node's parent and the last item will be the ultimate root item.
Last edited by dday9; Aug 28th, 2014 at 01:44 PM.
Reason: Added comments
-
Aug 28th, 2014, 03:09 PM
#3
Thread Starter
Hyperactive Member
Re: How to find parent of selected item in TreeView?
Okay, so how do I get the currently selected row as a TreeNode?
BTW, the WPF TreeView doesn't seem to have anything to do with TreeNodes. The WPF TreeView control comes from System.Windows.Controls, and there is no System.Windows.Controls.TreeNode that I can find. Please tell me that the WPF TreeView supports what I need to do...
-
Aug 28th, 2014, 03:35 PM
#4
Re: How to find parent of selected item in TreeView?
Ah... I did not see that this was WPF(I should've read better). I'll move this thread to the WPF forum.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|