Hasti Fallah

Hasti Fallah

  • NA
  • 61
  • 2.6k

Drag and Drop in WPF

Jan 7 2022 7:32 PM

hi.
im trying to Create drag and drop between two Listboxes.
i Add values Into listbox1 And when i want to Drag it into Listbox2 it fails.

i have to mention that There is no database or item binding.
i created text box and i add item from there

Here is my code:

private void Listbox1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    listbox1startsmousepose=e.GetPosition(null);
}

private void Listbox2_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    listbox2startsmousepose=e.GetPosition (null);
}

private void Listbox1_MouseMove(object sender, MouseEventArgs e)
{
    Point mPos = e.GetPosition(null);

    if (e.LeftButton == MouseButtonState.Pressed &&
        Math.Abs(mPos.X) > SystemParameters.MinimumHorizontalDragDistance &&
        Math.Abs(mPos.Y) > SystemParameters.MinimumVerticalDragDistance)
    {
        try
        {
            ListBoxItem selectedItem = (ListBoxItem)Listbox1.SelectedItem;
            Listbox1.Items.Remove(selectedItem);
      DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, selectedItem), DragDropEffects.Copy);
            if (selectedItem.Parent == null)
            {
                Listbox1.Items.Add(selectedItem);
            }
        }
        catch { }
    }
}

private void Listbox2_MouseMove(object sender, MouseEventArgs e)
{
    Point mPos = e.GetPosition(null);
    if (e.LeftButton == MouseButtonState.Pressed &&
        Math.Abs(mPos.X) > SystemParameters.MinimumHorizontalDragDistance &&
        Math.Abs(mPos.Y) > SystemParameters.MinimumVerticalDragDistance)
    {
        try
        {
            ListBoxItem selectedItem = (ListBoxItem)Listbox2.SelectedItem;
            Listbox2.Items.Remove(selectedItem);
            DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, selectedItem), DragDropEffects.Copy);
            if (selectedItem.Parent == null)
            {
                Listbox2.Items.Add(selectedItem);
            }
        }
        catch { }
    }
}

private void Listbox2_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetData(DataFormats.FileDrop) is ListBoxItem listItem)
    {
        Listbox2.Items.Add(listItem);
    }
}

private void Listbox1_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetData(DataFormats.FileDrop) is ListBoxItem listItem)
    {
        Listbox1.Items.Add(listItem);
    }
}

 


Answers (2)