Question

I have an element in XAML used to trigger a DragMove when you click on the element and hold down the mouse button.

<Grid>
    <CheckBox x:Name="myCheckBox" IsChecked="{Binding IsDragging}">I am red square dragging!</CheckBox>
    <Rectangle x:Name="myRect" Width="100" Height="100" Fill="Red"/>
</Grid>

The event handling is done code-behind the following way:

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        myRect.MouseLeftButtonDown += myRect_MouseLeftButtonDown;
        myRect.MouseLeftButtonUp += myRect_MouseLeftButtonUp;
    }

    void myRect_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        IsDragging = false;
    }

    void myRect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        IsDragging = true;
        DragMove();
    }

Even though dragging works, myRect_MouseLeftButtonUp is never called so IsDragging is never set to false after it is set to true. How do I make this work?

As a bonus, here is a gratuitous image of the element to coax you to answer this question.

enter image description here

No correct solution

OTHER TIPS

DragMove is a blocking event ending with MouseLeftButtonUp. The correct behavior can be induced using

    void myRect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        IsDragging = true;
        DragMove();            
        myRect.RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left)
        {
            RoutedEvent = MouseLeftButtonUpEvent
        });
    }

Also see C# WPF - DragMove and click

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