在WPF C#TreeView中获取选定项的父节点和子节点

时间:2019-02-01 15:45:15

标签: c# wpf treeview

我使用此代码填充了树形视图。 如何获得所有父节点以及子节点和根? (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;
}

我尝试了这段代码,它可以用于获取索引,但是我不能使用节点(父节点)

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();
}

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

在一般你的想法是正确的。

您需要的代码如下:

    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);
    }

结果将是:

enter image description here

https://github.com/KohrAhr/Q54482751上提供

完整的演示项目