TreeView控件根据可视界面大小智能打开关闭节点

就是动态载入节点的时候尽量不出垂直滚动条

是不是有人要求全部打开,有人要求全部关闭,有人要展开到2级.现在不用在烦恼了.

        private Dictionary<int, int> nodeCount=new Dictionary<int,int> ();

        /// <summary>
        /// 智能刷新树的展开关闭状态
        /// </summary>
        public void RefreshTreeview()
        {
            foreach (TreeNode tn in this.treeView1.Nodes)
            {
                ComputeNodeCount(tn);
            }

            Dictionary<int, int> nodeCount1 = nodeCount;
            for (int i = 0; i < nodeCount.Count; i++)
            { nodeCount1[i] = 0; }
            for (int i = 0; i < nodeCount.Count; i++)
            {
                for (int j = 0; j < nodeCount.Count; j++)
                {
                    if (j < i)
                        nodeCount1[i] += nodeCount[j];
                }
            }

            this.treeView1.CollapseAll();
            int ExpandLevel = nodeCount.Count;
            for (int i = 0; i < nodeCount.Count; i++) 
            {
                if (nodeCount1[i] >= this.treeView1.VisibleCount)
                {
                    ExpandLevel = i;
                    break;
                }
            }
            foreach (TreeNode tn in this.treeView1.Nodes)
            {
                Expand(tn, ExpandLevel-1);//递归
            }
                
        }
        /// <summary>
        /// 展开所有Level小于等于i的节点 递归
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="i"></param>
        private void Expand(TreeNode tn,int i)
        {
            if (tn.Level <= i)
                tn.Expand();
            foreach (TreeNode ntn in tn.Nodes)
            {
                Expand(ntn, i);
            }
        }
        /// <summary>
        /// 计算节点个数 递归
        /// </summary>
        /// <param name="tn"></param>
        private void ComputeNodeCount(TreeNode tn)
        {
            if (nodeCount.ContainsKey(tn.Level))
            {
                nodeCount[tn.Level]++;
            }
            else
            {
                nodeCount.Add(tn.Level, 1);
            }
            foreach (TreeNode ntn in tn.Nodes)
            {
                ComputeNodeCount(ntn);
            }
        }

 

 

举个例子来说明,我们有一个0级2个节点,1级4个节点,2级8个节点的TreeView,那程序中的数据是这样的

level 本节点数量 算法 展开到本级显示的节点数
0 2 2 2
1 4 2+4 6
2 8 2+4+8 14

 

posted @ 2012-06-29 20:21  Xheart  阅读(1803)  评论(2编辑  收藏  举报