Question

I created a usercontrol which contains a Canvas and a Button on the Canvas. To be able to move the button over the canvas I attached a DragBehavior shown below:

class DragOverCanvasBehavior : Behavior<FrameworkElement>
{
    private Point _mouseStartPosition;

    protected override void OnAttached()
    {

        AssociatedObject.MouseLeftButtonDown += (sender, e) =>
                                                {
                                                    _mouseStartPosition =                                                            e.GetPosition((Canvas) AssociatedObject.Parent);
                                                    AssociatedObject.CaptureMouse();
                                                };

        AssociatedObject.MouseLeftButtonUp += (sender, e) => AssociatedObject.ReleaseMouseCapture();

        AssociatedObject.MouseMove += (sender, e) =>
        {
            var point = e.GetPosition((Canvas)AssociatedObject.Parent) - _mouseStartPosition;
            if (AssociatedObject.IsMouseCaptured)
            {
                Canvas.SetTop(AssociatedObject, point.Y);
                Canvas.SetLeft(AssociatedObject, point.X);
            }
        };
    }
}  

For a business reason I need to move the canvas also if I hold and drag the canvas. I did it with a similar Behavior class which changes the Canvas margins and gives it the look as if it's moving along with mouse pointer on drag. This Behavior also captures mouse.

Now the problem is - If I click and drag the Button, the Canvas also gets Mouse events and starts getting dragged. How can I make sure that when I am dragging the Button the Canvas Behavior does not get mouse events.

I tried putting e.Handled = true in Behaviors but that did not work.

If I can find out that the Mouse is already Captured bu some other object, I can put condition in Behavior to not to capture it again.

Was it helpful?

Solution

Test for Mouse.Captured!= null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top