拖拽使用MVVM从WPF中删除/到多个列表框

时间:2016-03-30 11:53:11

标签: c# wpf mvvm drag-and-drop listbox

我有wget我动态创建(根据数据库中的团队数量)。 每个ListBoxes都包含用户对象。 我希望能够将用户从一个ListBox拖放到另一个ListBox。我能找到的所有示例都是从一个预定义的源列表拖放到另一个预定义的目标ListBox

如何实施?

1 个答案:

答案 0 :(得分:0)

我现在没有时间对此进行测试,但您是否可以尝试将Joby链接中的事件附加到动态创建的ListBox中?它看起来像是:

// Create an instance of the control
var control = Activator.CreateInstance(ListBox);

control.PreviewMouseLeftButtonDown += ListBox_PreviewMouseLeftButtonDown;
control.Drop += ListBox_Drop;

为了完整性,如果源链接消失,以下是来自http://www.c-sharpcorner.com/uploadfile/dpatra/drag-and-drop-item-in-listbox-in-wpf/的事件处理程序

ListBox dragSource = null;
private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
   ListBox parent = (ListBox)sender;
   dragSource = parent;
   object data = GetDataFromListBox(dragSource, e.GetPosition(parent));

   if (data != null)
   {
      DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
   }
}

#region GetDataFromListBox(ListBox,Point)
private static object GetDataFromListBox(ListBox source, Point point)
{
    UIElement element = source.InputHitTest(point) as UIElement;
    if (element != null)
    {
       object data = DependencyProperty.UnsetValue;
       while (data == DependencyProperty.UnsetValue)
       {
           data = source.ItemContainerGenerator.ItemFromContainer(element);
           if (data == DependencyProperty.UnsetValue)
           {
              element = VisualTreeHelper.GetParent(element) as UIElement;
           }
           if (element == source)
           {
              return null;
           }
        }
        if (data != DependencyProperty.UnsetValue)
        {
           return data;
        }
     }

     return null;
 }

#endregion

private void ListBox_Drop(object sender, DragEventArgs e)
{
   ListBox parent = (ListBox)sender;
   object data = e.Data.GetData(typeof(string));
   ((IList)dragSource.ItemsSource).Remove(data);
   parent.Items.Add(data);
}