0
votes

I used this code to fill a treeview. How can get all parent nodes and child node and root? (visual studio 2017 WPF) example

private TreeViewItem GetTreeView(string text, string imagePath)
{ TreeViewItem item = new TreeViewItem();
item.IsExpanded = true;
// create stack panel
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
// create Image
Image image = new Image();
image.Source = new BitmapImage(new ri("pack://application:,,/Image/" + 
imagePath));
// Label
Label lbl = new Label();
lbl.Content = text;
lbl.Content = text;
// Add into stack
stack.Children.Add(image);
stack.Children.Add(lbl);
// assign stack to header
item.Header = stack;
return item;
}

I tried this code, it works for get the index but I can not take the nodes (parent)

var tree = sender as TreeView;
if (tree.SelectedValue != null)
{
index++;
TreeViewItem itemLvl = tree.SelectedItem as TreeViewItem;
ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(itemLvl);
while (parent != null && parent.GetType() == typeof(TreeViewItem))
{
index++;
parent = ItemsControl.ItemsControlFromItemContainer(parent);
//var sp = ?????.Header as StackPanel;
//var tb = sp.Children[1] as Label;
//var im = sp.Children[0] as Image;
//string test= sp.Children[1].ToString();
}

Thanks for your help

1

1 Answers

0
votes

in generally your idea is correct.

code you need will be looks like:

    private void TvMain_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        string result = "";

        TreeView tree = (TreeView) sender;

        TreeViewItem item = (TreeViewItem) tree.SelectedItem;
        result = item.Header.ToString();

        while (item.Parent != null && item.Parent is TreeViewItem)
        {
            item = (TreeViewItem)item.Parent;
            result = item.Header.ToString() + " \\ " + result;
        }

        MessageBox.Show(result);
    }

result will be:

enter image description here

full demo project available on https://github.com/KohrAhr/Q54482751