简体   繁体   English

如何在Treeview控件中交换项目?

[英]How to swap items in treeview control?

I have a treeview control: 我有一个treeview控件:

  • Parent Item 1 父项1
    • Child Item 1 儿童项目1
    • Child Item 2 子项2
    • Child Item 3 儿童项目3
  • Parent Item 2 父项2
    • Child Item 1 儿童项目1
    • Child Item 2 子项2
    • Child Item 3 儿童项目3
  • Parent Item 3 父项3
    • Child Item 1 儿童项目1
    • Child Item 2 子项2
    • Child Item 3 儿童项目3

I want to move, for example Parent Item 2 , up or down with its child items as well as i want to move child items up/down for its parent level. 我想上下移动它的子项,例如“ 父项2” ,也想上/下移动其父级的子项。

ps I've done this with database, but it's performance issue to rebind treeview every move operation. ps我已经使用数据库完成了此操作,但是重新绑定树视图的每个移动操作都是性能问题。

I have used a modified version of the code found here here in the past to drag/drop UI items in a TreeView 我过去曾 这里找到 此处 使用的代码的修改版本,以将其拖放到TreeView

Basically it finds the parent control that holds the collection, uses the ItemContainerGenerator to find the container that holds the dragged item, then moves the container to the new location within the parent control 基本上,它会找到保存集合的父控件,使用ItemContainerGenerator查找包含拖动项的容器,然后将容器移动到父控件内的新位置

The following example is workable for me. 以下示例对我来说是可行的。 Select a child node and swap with its parent node. 选择一个子节点并与其父节点交换。

TreeNode currentNode, targetNode;
currentNode = TreeView1.SelectedNode;
targetNode = currentNode.Parent;
if (currentNode.Parent != null)
{
    CopyedTreeNode = (TreeNode)targetNode.Clone();
    CopyedTreeNode02 = (TreeNode)currentNode.Clone();

    targetNode.Text = CopyedTreeNode02.Text;
    targetNode.Tag = CopyedTreeNode02.Tag;
    targetNode.ImageIndex = CopyedTreeNode02.ImageIndex;
    targetNode.SelectedImageIndex = CopyedTreeNode02.SelectedImageIndex;

    currentNode.Text = CopyedTreeNode.Text;
    currentNode.Tag = CopyedTreeNode.Tag;
    currentNode.ImageIndex = CopyedTreeNode.ImageIndex;
    currentNode.SelectedImageIndex = CopyedTreeNode.SelectedImageIndex;

    CopyedTreeNode.Remove();
    CopyedTreeNode02.Remove();
}

Perhaps a two way binding with your custom object ? 也许通过两种方式与您的自定义对象绑定? You can add a custom sorter for the treeview View model by order property for example... 您可以通过order属性为treeview视图模型添加自定义排序器,例如...

Couldn't that work? 那行不通吗?

TreeNode node1 = treeView.Nodes[1];
TreeNode node2 = treeView.Nodes[2];
treeView.Nodes[1] = node2;
treeView.Nodes[2] = node1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM