#711 – Changing the Mouse Cursor While Dragging

You can change the mouse cursor during a drag-and-drop operation by handling the GiveFeedback event for the drag source.  The GiveFeedbackEventArgs.Effects property will indicate the current effect, depending on the mouse position.  You can set the mouse cursor based on the effect.

In the example below, we change the mouse to a “hand” whenever the effect is Copy, indicating that we’re allowed to drop the data.

    <StackPanel Orientation="Vertical" HorizontalAlignment="Center" Margin="45">
        <Label Content="Data to drag" Background="AliceBlue" Padding="15,10" Margin="10"
               MouseLeftButtonDown="Label_MouseLeftButtonDown"
               GiveFeedback="Label_GiveFeedback"/>
        <Label Content="Drag to here" Background="MediumSpringGreen" Padding="15,10" Margin="10"
               AllowDrop="True" Drop="Label_Drop"/>
    </StackPanel>
        private void Label_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataObject data = new DataObject(DataFormats.Text, ((Label)e.Source).Content);

            DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
        }

        private void Label_Drop(object sender, DragEventArgs e)
        {
            ((Label)e.Source).Content = (string)e.Data.GetData(DataFormats.Text);
        }

        private void Label_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            if (e.Effects == DragDropEffects.Copy)
            {
                e.UseDefaultCursors = false;
                Mouse.SetCursor(Cursors.Hand);
            }
            else
                e.UseDefaultCursors = true;

            e.Handled = true;
        }

711-001
711-002

#709 – Changing the Cursor

You can change the image displayed as a cursor in your WPF application by setting the Cursor property of any FrameworkElement.    You can set the cursor to one of the predefined Cursor objects in the System.Windows.Input.Cursors class.

In the example below, we set the cursor to a hand whenever the user moves the mouse over the blue label. Setting the Cursor property to null resets it to the default cursor.

    <StackPanel Orientation="Vertical" HorizontalAlignment="Center" Margin="45">
        <Label Content="Hey, move your mouse over me !" Background="AliceBlue" Padding="15,10"
                MouseEnter="Label_MouseEnter" MouseLeave="Label_MouseLeave"/>
    </StackPanel>

 

        private void Label_MouseEnter(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void Label_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = null;
        }

709-001
709-002