我们假设以下情况:
控件(例如,按钮)具有附加行为以启用拖放操作
<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在完成拖放操作后返回.
是的,“启动拖放操作”令人困惑,因为它可以被读作“开始拖放并返回”:
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
}
}
}