c# - PreviewMouseLeftButtonDown 干扰点击选择

标签 c# wpf xaml drag-and-drop listbox

<分区>

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

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

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

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

最佳答案

为避免干扰正常选择,通常让用户在通过 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;
        }
    }
}

关于c# - PreviewMouseLeftButtonDown 干扰点击选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14103159/

相关文章:

c# - 没有为命令对象设置命令文本

c# - wpf 未处理的异常

wpf - 如何减少 RadioButton 绑定(bind)代码?

c# - WPF 中的类概念

c# - xaml解析异常问题仅在win7上

c# - 绑定(bind) : Visualize a list of unnamed booleans using DataTemplate and bindings

c# - 等待后任务继续不工作

c# - 取消可观察集合上的集合更改事件

c# - 如何并行遍历动态值字典?

WPF 命令绑定(bind)