Devexpress TreeList选择父级联动

Posted .Net C#相关记录和学习笔记的共享.支持开源

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Devexpress TreeList选择父级联动相关的知识,希望对你有一定的参考价值。

Treelist当显示复选框后,父级和子级的复选框没有关联,使用过程中很不便,如图所示

image

自己给treelist添加父子级联动

/// <summary>
    /// 初始化TreeList,父子节点选择关联
    /// </summary>
    public class TreeListInitial
    {
        TreeList Tree;
        /// <summary>
        /// 初始化TreeList,父子节点选择关联
        /// </summary>
        /// <param name="tree"></param>
        public TreeListInitial(TreeList tree)
        {
            Tree = tree;
            tree.BeforeCheckNode += tree_BeforeCheckNode;
            tree.AfterCheckNode += tree_AfterCheckNode;
        }

        public bool AllowCheck = true;

        public void tree_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            SetCheckedChildNodes(e.Node, e.Node.CheckState);
            SetCheckedParentNodes(e.Node, e.Node.CheckState);
        }

        void tree_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            e.CanCheck = AllowCheck;


            e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
        }

        public void SetNodeCheckState(TreeListNode node, CheckState checkState)
        {
            Tree.SetNodeCheckState(node, CheckState.Checked);
            SetCheckedChildNodes(node, CheckState.Checked);
            SetCheckedParentNodes(node, CheckState.Checked);
        }

        void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i].CheckState = check;
                SetCheckedChildNodes(node.Nodes[i], check);

            }
        }
        void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool b = false;
                CheckState state;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    state = (CheckState)node.ParentNode.Nodes[i].CheckState;
                    if (!check.Equals(state))
                    {
                        b = !b;
                        break;
                    }
                }
                node.ParentNode.CheckState = b ? CheckState.Indeterminate : check;
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }


    }

在窗体加载的时候传入需要联动的treelist实例化即可

new TreeListInitial(tree_Module)

效果图:

image

以上是关于Devexpress TreeList选择父级联动的主要内容,如果未能解决你的问题,请参考以下文章

devexpress treelist 绑定数据时让部分节点默认选择

DevExpress之TreeList复选框实现

[DevExpress]treeList1背景色设置与自定义图标

DevExpress TreeList GridView 样式设置

devexpress treelist 过滤

devexpress treelist怎么添加自定义节点?