欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF MVVM Treeview 节点替换(编辑)

程序员文章站 2022-06-08 14:02:17
...

对自己写的树控件 WPF MVVM TreeView 做了个延伸,原来只有添加和删除节点的方法,现在再新增一个节点替换的方法,即节点的编辑,代码如下

 //只替换当前新的节点,不替换子节点
        public virtual void Replace(string oldNodeId, TNode newNode)
        {
            if (TreeData == null || !string.Equals(oldNodeId, newNode?.TreeId) || !TreeItemDic.ContainsKey(oldNodeId))
            {
                return;
            }

            var oldNode = TreeItemDic.GetItem(oldNodeId);
            var oldPNodeChild = TreeChildrenDic.GetItem(oldNode.TreePid);
            oldPNodeChild = oldPNodeChild ?? TreeRoot;

            if (oldPNodeChild == null)
            {
                return;
            }

            Replace(oldNode, newNode, oldPNodeChild);
        }
        private void Replace(TNode oldNode, TNode newNode, ObservableCollection<TNode> oldPNodeChild)
        {
            var indexPNodeChild = oldPNodeChild.IndexOf(oldNode);
            var indexTreeData = TreeData.IndexOf(oldNode);

            if (indexPNodeChild < 0 || indexTreeData < 0)
            {
                return;
            }

            var oldNodeId = oldNode.TreeId;

            if (oldNode.Children == null)
            {
                TreeChildrenDic.RemoveItem(oldNodeId);
                oldNode.Children = new ObservableCollection<TNode>();
                TreeChildrenDic.AddItem(oldNodeId, oldNode.Children);
            }

            newNode.Children = oldNode.Children;

            oldPNodeChild.Insert(indexPNodeChild, newNode);
            oldPNodeChild.Remove(oldNode);

            TreeData.Insert(indexTreeData, newNode);
            TreeData.Remove(oldNode);

            TreeItemDic.RemoveItem(oldNodeId);
            TreeItemDic.AddItem(oldNodeId, newNode);
        }

PS:原理就是将老节点的内存地址替换成了新的节点,其中只替换当前新的节点,不替换子节点(将子节点Children覆值给新节点)

相关标签: WPF C#