c# - 发起者如何确定拖动已经结束?

标签 c# wpf drag-and-drop

让我们假设以下情况: 控件(例如按钮)具有启用拖放操作的附加行为

<Button Content="test"> 
    <i:Interaction.Behaviors>
        <SimpleDragBehavior/>
    </i:Interaction.Behaviors>
</Button>

和 SimpleDragBehavior

public class SimpleDragBehavior: Behavior<Button>
{       
    protected override void OnAttached ()
    {           
        AssociatedObject.MouseLeftButtonDown += OnAssociatedObjectMouseLeftButtonDown;
        AssociatedObject.MouseLeftButtonUp   += OnAssociatedObjectMouseLeftButtonUp;
        AssociatedObject.MouseMove           += OnAssociatedObjectMouseMove;

        mouseIsDown = false;
    }       

    private bool  mouseIsDown;

    private void OnAssociatedObjectMouseMove (object sender, MouseEventArgs e)
    {
        if (mouseIsDown)
        {
            AssociatedObject.Background = new SolidColorBrush(Colors.Red);

            DragDrop.DoDragDrop((DependencyObject)sender,
                                AssociatedObject.Content,
                                DragDropEffects.Link);
        }
    }

    private void OnAssociatedObjectMouseLeftButtonUp (object sender, MouseButtonEventArgs e)
    {
        mouseIsDown = false;
    }

    private void OnAssociatedObjectMouseLeftButtonDown (object sender, MouseButtonEventArgs e)
    {
        mouseIsDown = true;
    }       
}

现在的任务是确定拖动何时结束,恢复按钮的原始背景。 这在放置在放置目标上时没有问题。但是我如何识别不是落目标的东西?在最坏的情况下:在窗外?

最佳答案

DragDrop.DoDragDrop 返回 after 拖放操作完成。
是的,“启动拖放操作” 令人困惑,因为它可以理解为“开始拖放并返回”:

private void OnAssociatedObjectMouseMove (object sender, MouseEventArgs e)
{
    if (mouseIsDown)
    {
        AssociatedObject.Background = new SolidColorBrush(Colors.Red);

        var effects = DragDrop.DoDragDrop((DependencyObject)sender,
                            AssociatedObject.Content,
                            DragDropEffects.Link);

        // this line will be executed, when drag/drop will complete:
        AssociatedObject.Background = //restore color here;

        if (effects == DragDropEffects.None)
        {
            // nothing was dragged
        }
        else
        {
            // inspect operation result here
        }
    }
}

关于c# - 发起者如何确定拖动已经结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32945139/

相关文章:

wpf - 路径数据属性的M,L,XAML是什么

c# - 带有字符串数组的 DataTemplate

javascript - 拖放和提交文件以上传

c# - 根据当前上下文显示RibbonTab的内容

css - -webkit-user-drag css 属性是什么?

Qt EnsureVisible() 在 QScrollArea 中不起作用

c# - 显式转换

c# - C vs C++ vs C#用于测试嵌入式关键软件

c# - System.Windows.Forms.Trackbar - 如何防止用户拖动 slider ?

c# - 寻找一种数据包描述语言(最好使用C#实现)