C#学习TreeView以及显示所有父级的方法

问题描述 投票:0回答:1

我第一次使用 TreeView,现在,我设定了一个目标,即能够显示给定孩子的所有父母,作为开始。 目标已经完成,但对我来说,这段代码可以写得更好。有什么意见,或者我是否做错了什么?

//Get selected TreeView item and parents
private void TreeviewMain_SelectedItem(object sender, RoutedEventArgs e)
{
    TreeViewItem? selectedParent = e.OriginalSource as TreeViewItem;
    TreeViewItem selectedItem = (TreeViewItem)MainTestList.SelectedItem;
    string parentPath = "";

    if (selectedParent != null)
    {
        parentPath = GetTreeviewParent(selectedParent);

    }

    if (selectedItem != null)
    {
        string finalItemPath = parentPath + selectedItem.Header.ToString();
        CurrentItem.Text = finalItemPath;
    }
}

// Form a string of parent names
public string GetTreeviewParent(TreeViewItem item)
{
    DependencyObject parent = VisualTreeHelper.GetParent(item);
    string parentPath = ">";
    while (!(parent is TreeView))
    {
        parent = VisualTreeHelper.GetParent(parent);

        if (parent != null)
        {
            ItemsControl parentItem = parent as ItemsControl;
            TreeViewItem parentName = parentItem as TreeViewItem;
            if (parentName != null)
            {
                parentPath = ">" + parentName.Header.ToString() + parentPath;
            }
        }
    }

    return parentPath;
}

Success!

在弄清楚它是如何工作的时候,我尝试了一些东西,但这是迄今为止最干净的一个......但至少对我来说它仍然看起来一团糟

c# treeview
1个回答
0
投票

我稍微重构了你的代码。逻辑上没问题,但我使用了一些 C# 功能,比如 模式匹配 可以让你的代码简洁一点:

//Get selected TreeView item and parents
private void TreeviewMain_SelectedItem(object sender, RoutedEventArgs e)
{
    var parentPath = e.OriginalSource is TreeViewItem selectedParent
        ? GetTreeviewParent(selectedParent)
        : "";

    if (MainTestList.SelectedItem is TreeViewItem selectedItem)
        CurrentItem.Text = parentPath + selectedItem.Header;
}

// Form a string of parent names
public string GetTreeviewParent(TreeViewItem item)
{
    DependencyObject parent = VisualTreeHelper.GetParent(item);
    string parentPath = ">";
    while (parent != null && parent is not TreeView)
    {
        parent = VisualTreeHelper.GetParent(parent);

        if (parent == null)
            continue;
        
        if (parent is TreeViewItem parentName)
            parentPath = ">" + parentName.Header.ToString() + parentPath;
    }

    return parentPath;
}
© www.soinside.com 2019 - 2024. All rights reserved.