Reputation: 523
I want to get the root node of selected item in TreeView, for example, if I've:
Italy
Serie A
and the user select Serie A
, in the code was return Italy parent root.
So I've create this variable inside a method:
var country = FindRootNode(nation_team.SelectedItem);
and this is the method:
private TreeViewItem FindRootNode(TreeView treeNode)
{
while (treeNode.Parent != null)
{
treeNode = (TreeView)treeNode.Parent;
}
return treeNode;
}
but I'm not sure if this code is correct, anyway, return treeNode
is underlined in red, with this error:
Can not implicitly convert type System.Windows.Controls.TreeView in System.Windows.Controls.TreeViewItem
Upvotes: 0
Views: 183
Reputation: 2309
You are assigning treeNode
which is a TreeView
object to a TreeViewItem
object.
With this line :
treeNode = (TreeView)treeNode.Parent;
Before using it make sure you are casting the SelectedItem to TreeViewItem like so :
FindRootNode(nation_team.SelectedItem as TreeViewItem)
What you are looking for is this recursive approach :
private TreeViewItem FindRootNode(TreeViewItem currentItem){
if(currentItem == null) return null;
var tvi = (TreeViewItem)currentItem.Parent;
if(tvi == null){
return currentItem;
}
else{
return FindRootNode(tvi);
}
}
Or this iterative one :
private TreeViewItem FindRootNode(TreeViewItem currentItem){
if(currentItem == null) return null;
while(currentItem.Parent as TreeViewItem!= null){
currentItem = currentItem.Parent as TreeViewItem;
}
return currentItem;
}
Upvotes: 1