Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change cursor when dragging in WPF

I'm using this great drag/drop framework: http://code.google.com/p/gong-wpf-dragdrop/ I have two listboxes - A and B. When I drag from B to A, I want the mouse cursor to change as soon as the cursor is within the area of listbox A.

I've almost got it. By using the IDropTarget interface as follows:

void IDropTarget.DragOver(DragOver drag)
{
 drag.Effects = DragDropEffects.Copy | DragDropEffects.Move;

 // some logic to determine if hovering over listbox A
 // ...

 if (hoveringOverListA)
 {
  ListBoxA.Cursor =  ((FrameworkElement) Application.Current.Resources["ListboxACursor"]).Cursor;
 }
}

The only problem is, while I'm dragging over the cursor that shows is the the operation not allowed one (the black circle with the line through it). As soon as I release the mouse, then I see my ListboxACursor appear. So it's like it's a delayed reaction, like it's waiting for me to Drop instead of doing it while I'm DragOver'ing.

If anyone can see what is wrong with the code, I would greatly appreciate it. I have a feeling it might be to do with the DragDropEffects but it's mainly a hunch.

like image 892
theqs1000 Avatar asked Jan 15 '13 16:01

theqs1000


2 Answers

Answering this question because it's the top Google result.

protected override void OnGiveFeedback(System.Windows.GiveFeedbackEventArgs e)
{
    Mouse.SetCursor(Cursors.Hand);
    e.Handled = true;
}

This method should be defined on the drag source. It's critical that you flag the event as handled and that you DO NOT call base.OnGiveFeedback, as doing either will result in the default drag cursor overriding your changes.

Notice how I'm also using Mouse.SetCursor instead of the more obvious FrameworkElement.Cursor. The latter is a persistent property of the drag source element, and it's unlikely that you actually want to change

like image 54
Artfunkel Avatar answered Oct 11 '22 15:10

Artfunkel


That is because Windows tries to use its own cursor to ensure a default look&feel. You can avoid this by explicitely disabling the default cursor. See GiveFeedback event in this tutorial

 private void DragSource_GiveFeedback(object sender, GiveFeedbackEventArgs e)
 {
   e.UseDefaultCursors = e.Effect != DragDropEffects.Copy;
 }
like image 27
Matthias Avatar answered Oct 11 '22 14:10

Matthias