I understand that programming in C# with WPF is different from traditional C# procedures so most of the online material do not state what I need.
I have a TreeView control in my WPF Window and I have parent nodes and child nodes in it. I would like to store them in a List of type Node (id, name, parent).
I got the name of the selected item/node using this:
private void TreeViewItem_OnItemSelected(object sender, RoutedEventArgs e)
{
TreeViewItem item = treeView.SelectedItem as TreeViewItem;
nameTxt.Text = item.Header.ToString();
}
And I tried getting the Parent of the child node immediately before it using this:
TreeViewItem item = treeView.SelectedItem as TreeViewItem;
nameTxt.Text = item.Parent.ToString();
However, this returns the Root Parent (A) instead of the child's parent (which is 2).
What changes should I make to get the child's immediate parent instead of the root parent? :)
EDIT: Here's the XAML
<TreeView Name="treeView" HorizontalAlignment="Left" Height="564" Margin="10,68,0,0" VerticalAlignment="Top" Width="363">
<TreeViewItem TreeViewItem.Selected="TreeViewItem_OnItemSelected" Header="A" IsExpanded="True" Height="554" FontSize="18">
<TreeViewItem Header="1" />
<TreeViewItem Header="2" />
</TreeViewItem>
</TreeView>
Created a small example to demonstrate your problem
In MainWindow.xaml
<TreeView Name="tree">
<TreeView>
<TreeViewItem Header="North America" Selected="TreeViewItem_OnItemSelected">
<TreeViewItem Header="USA">
<TreeViewItem Header="New York"/>
<TreeViewItem Header="Las Vegas"/>
<TreeViewItem Header="Washington"/>
</TreeViewItem>
<TreeViewItem Header="Canada">
<TreeViewItem Header="Toronto"/>
<TreeViewItem Header="Quebec"/>
<TreeViewItem Header="Montreal"/>
</TreeViewItem>
<TreeViewItem Header="Mexico"></TreeViewItem>
</TreeViewItem>
</TreeView>
</TreeView>
in Code Behind i.e MainWindow.xaml.cs
private void TreeViewItem_OnItemSelected(object sender, RoutedEventArgs e)
{
TreeViewItem item = e.OriginalSource as TreeViewItem;
if (item != null)
{
ItemsControl parent = GetSelectedTreeViewItemParent(item);
TreeViewItem treeitem = parent as TreeViewItem;
string MyValue= treeitem .Header.ToString();//Gets you the immediate parent
}
}
public ItemsControl GetSelectedTreeViewItemParent(TreeViewItem item)
{
DependencyObject parent = VisualTreeHelper.GetParent(item);
while (!(parent is TreeViewItem || parent is TreeView))
{
parent = VisualTreeHelper.GetParent(parent);
}
return parent as ItemsControl;
}
And its done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With