65.9K
CodeProject 正在变化。 阅读更多。
Home

主页上的可折叠树视图

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (2投票s)

2009 年 10 月 30 日

CPOL

1分钟阅读

viewsIcon

32772

downloadIcon

1112

演示了如何在主页面中使用可折叠的TreeView控件。

引言

场景:我想要一个可折叠的菜单(TreeView),它只显示当前部分/部门的菜单项。例如,如果在人力资源部门的节点中,则只在菜单上显示人力资源子菜单项。我需要在主页面中使用这个菜单(这肯定会使事情变得复杂!)。

在主页面中使用TreeView控件可能是一个难题,因为每次访问另一个页面时,该控件都会被刷新。有几种解决方案来解决这个问题。我曾经遇到过一种解决方案,你需要将控件的结构加载到ViewState中;我也得到一个建议是“购买”(嘿,我是一名开发者)一个控件。

我决定修改现有的TreeView控件。当我加载页面时,我会检查页面的路径并从TreeView中获取相应的节点。然后,我会根据需要处理这些节点。

使用代码

在将节点绑定到TreeView时,我们会检查当前节点是否指向当前页面。如果是,我们会将该节点设置为选定的节点。

剩下的就顺理成章了。可以随意操作所选节点的父节点。你还可以指定默认行为,例如当打开不在站点地图中的页面时。

protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
{
    //make the node that links to the current page the selected node.
    string currPage = Request.CurrentExecutionFilePath;

    if (currPage == e.Node.NavigateUrl)
    {
        e.Node.Select();
    }
}

protected void ProcessChildNode(string selNodePath, TreeNode tsn)
{
    //check child nodes
    if (tsn.ChildNodes.Count > 0)
    {

        foreach (TreeNode tsnChild in tsn.ChildNodes)
        {
            //use recursion for deeper tree levels
            if (tsnChild.ChildNodes.Count > 0)
            {
                //process child node
                ProcessChildNode(selNodePath, tsnChild);
            }
            if (selNodePath.Contains(tsnChild.ValuePath.ToString()))
            {
                tsnChild.Expand();
            }
            if (tsnChild.ChildNodes.Count > 0)
            {
                tsnChild.SelectAction = TreeNodeSelectAction.Expand;
            }
        }
    }
}
© . All rights reserved.