在TreeView中上下移动节点 [英] Shifting nodes up and down in a TreeView

查看:416
本文介绍了在TreeView中上下移动节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有一个包含TreeView的UserControl.该TreeView具有ViewModel和与其相关的模型.我想这样做,以便通过单击按钮可以在整个树中上下移动节点.这类似于在listBox上可以实现的功能.

作为指导,我正在使用解决方案

MVVM的主要思想是不使用诸如treeView.Items.Add()或treeView.GetAllChildren()之类的东西,或者不使用TreeView中需要的任何方法. /p>

MVVM模式表示您不关心View,也不了解View或View内部的任何控件.

因此,如果您的ViewModel中有一个ObservableCollection作为ItemsSource,则只需要在其中移动项目,TreeView就会跟随您.

就这么简单.您的TreeView只需要知道ObservableCollection在ViewModel中的放置位置即可.

每当您在ObservableCollection内部进行更改时,都会触发具有适当事件参数的藏品更改事件,该事件参数包含有关是否添加新项或转移项的信息.这就是TreeView知道该怎么做的方式.

In my program I have a UserControl that contains a TreeView. That TreeView has a ViewModel and a Model relating to it. I would like to make it so that by clicking buttons, I can shift nodes up and down throughout the tree. This is similar to what one might implement on a listBox.

As a guide, I am using this article.

I am implementing the following functions into the code-behind of the UserControl for which the TreeView exists.

//Move up
private void moveUp_Click(object sender, RoutedEventArgs e)
{
     if(UCViewModel.TreeView.SelectedItem != null)
     {
          if(UCViewModel.TreeView.SelectedItem is TreeModel)
          {
               TreeModel tm = UCViewModel.TreeView.SelectedItem as TreeModel;
               if(tm.Rank != 1)
               {

               }
          }
     }
}
private void MoveUp(TreeModel tm)
{                                //My guess on how to call the equivalent command...
      foreach (TreeModel item in // **UCViewModel.TreeView.GetAllChildren....? )
      {

      }
}

Because my structure is different, and I am actually implementing an ObservableCollection as a TreeView, I do not have access to the same methods as the code in the example.

The following lines are the lines that I am concerned about...

  • TreeView.Items();

  • TreeView.Items.Clear();

  • TreeView.Items.Add();

How can I make the equivalent calls with the way my TreeView is setup? Please let me know if more code would be helpful.

解决方案

The main idea of MVVM is not to use anything like treeView.Items.Add() or treeView.GetAllChildren() or whatever method you need from TreeView.

MVVM Pattern says you dont care about View and you dont know about the View or any control inside the View.

Therefore if you have an ObservableCollection as ItemsSource in your ViewModel you just need to move items there and the TreeView will follow you.

As simple as that. Your TreeView just needs to know where the ObservableCollection is placed inside your ViewModel.

Whenever you change something inside ObservableCollection you trigger collection changed event with appropriate event arguments holding information whether you added new items or shifted items around. That is how TreeView will know what to do.

这篇关于在TreeView中上下移动节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆