SalysBruoga
SalysBruoga

Reputation: 1045

C# WPF MouseLeftButtonUp event not firing when also using MouseMove

I have the following XAML code in my WPF test application:

<Canvas x:Name="canvas"
       HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
       Background="CornflowerBlue" MouseMove="canvas_MouseMove"
       MouseLeftButtonUp="canvas_MouseLeftButtonUp"
/>

And in my .cs file:

private const int Radius = 10;
private Ellipse _prev;

private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if (this._prev != null)
        canvas.Children.Remove(this._prev);
    var pos = e.GetPosition(canvas);
    var c = new Ellipse()
    {
        Height = 2 * Radius,
        Width = 2 * Radius,
        Fill = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)),
    };
    double x = pos.X - Radius;
    double y = pos.Y - Radius;
    Canvas.SetTop(c, y);
    Canvas.SetLeft(c, x);
    canvas.Children.Add(c);
}

private void canvas_MouseMove(object sender, MouseEventArgs e)
{
    if(e.LeftButton == MouseButtonState.Pressed)
    {
        if (this._prev != null)
            canvas.Children.Remove(this._prev);
        var pos = e.GetPosition(canvas);
        _prev = new Ellipse()
        {
            Height = 2 * Radius,
            Width = 2 * Radius,
            Fill = new SolidColorBrush(Color.FromArgb(100, 255, 0, 0)),
        };
        double x = pos.X - Radius;
        double y = pos.Y - Radius;
        Canvas.SetTop(_prev, y);
        Canvas.SetLeft(_prev, x);
        canvas.Children.Add(_prev);
    }
}

What I want to do is basically when a user click the left mouse button and drags around, a red circle with a little bit of alpha follows the cursor. When the user releases the mouse, the red circle stays there with no more alpha coloring. Seems like a pretty simple task, however the MouseLeftButtonUp event only fires when I don't drag the mouse around prior to releasing it. What am I doing wrong here?

Upvotes: 1

Views: 859

Answers (1)

melihceyhan
melihceyhan

Reputation: 42

you are always removing and adding ellipse to canvas in canvas_MouseMove function. if you try changing the position of ellipse in canvas_MouseMove you can do what you want

Upvotes: 2

Related Questions