1

我已实现此代码以在列表框中执行拖动功能。

http://www.c-sharpcorner.com/uploadfile/dpatra/drag-and-drop-item-in-listbox-in-wpf/

但意识到事件 PreviewMouseLeftButtonDown 会干扰 clic 选择。所以当我想选择一个项目时,我必须在项目中单击两次。

我应该修改什么来修复这个错误?

4

1 回答 1

4

为避免干扰正常选择,通常在您通过 DragDrop.DoDragDrop() 实际执行拖放操作之前让用户将项目拖动几个像素(在您的示例中,正是此调用中断了正常的单击选择)。

一种方法是稍微扩展您的示例,并通过侦听 ListBox 的 PreviewMouseMove 和 PreviewMouseLeftButtonUp 事件以及 PreviewMouseLeftButtonDown 事件来跟踪“潜在的拖动”:

<ListBox x:Name="lbOne" 
         PreviewMouseLeftButtonDown="ListBox_PreviewMouseLeftButtonDown"
         PreviewMouseMove="ListBox_PreviewMouseMove"
         PreviewMouseLeftButtonUp="ListBox_PreviewMouseLeftButtonUp"
         ... />

请注意我们在这里如何使用potentialDragStartPoint,以及如何将大量代码从 ListBox_PreviewMouseLeftButtonDown 移动到 ListBox_PreviewMouseMove:

ListBox dragSource = null;
Point? potentialDragStartPoint = null;

private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (potentialDragStartPoint == null)
    {
        ListBox parent = (ListBox)sender;
        potentialDragStartPoint = e.GetPosition(parent);
    }
}

private void ListBox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    potentialDragStartPoint = null;
}

private void ListBox_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if (potentialDragStartPoint == null) { return; }

    ListBox parent = (ListBox)sender;
    var dragPoint = e.GetPosition(parent);

    Vector potentialDragLength = dragPoint - potentialDragStartPoint.Value;
    if (potentialDragLength.Length > 5)
    {
        dragSource = parent;
        object data = GetDataFromListBox(dragSource, potentialDragStartPoint.Value);

        if (data != null)
        {
            DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
            potentialDragStartPoint = null;
        }
    }
}
于 2012-12-31T17:06:55.260 回答