Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not MouseLeftButtonUp fire in WPF?

Why does not the MouseLeftButtonUp on my Canvas fire in my WPF app? Here is the XAML:

<Grid Height="300" Width="400">
    <Canvas Name="canvas" MouseMove="canvas_MouseMove" MouseLeftButtonUp="canvas_MouseLeftButtonUp" Background="LightGray"/>
</Grid>

And the code:

    private bool hasClicked = false;

    public Window1()
    {
        InitializeComponent();
    }

    private void canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (!this.hasClicked)
        {
            this.Cursor = Cursors.None;
            this.canvas.Children.Clear();
            this.insertRectangle(false);
        }
    }

    private void insertRectangle(bool filled)
    {
        Rectangle rect = createRect(filled);
        Point pos = Mouse.GetPosition(this.canvas);
        Canvas.SetLeft(rect, pos.X);
        Canvas.SetTop(rect, pos.Y);
        this.canvas.Children.Add(rect);
    }

    private Rectangle createRect(bool fill)
    {
        Rectangle rect = new Rectangle();
        rect.Height = 50;
        rect.Width = 120;
        if (fill)
        {
            rect.Fill = new SolidColorBrush(Colors.Green);
        }
        else
        {
            rect.Stroke = new SolidColorBrush(Colors.Green);
        }
        return rect;
    }

    private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        this.hasClicked = true;
        this.insertRectangle(true);
        this.Cursor = Cursors.Arrow;
    }

Edit: I have tried adding a background colour to the canvas, but still the event is not fired. It seems like the MouseMove somehow overrides the MouseLeftButtonUp.

Edit2: If I remove the MouseMove event, mouseLeftButtonUp will fire.

Edit3: Bigger code example. In the insertRectangle method, if I use

 Canvas.SetTop(rect, 50);
 instead of 
 Canvas.SetTop(rect, pos.Y);

the events fires just fine.

like image 215
eflles Avatar asked Aug 06 '26 19:08

eflles


1 Answers

If you don't set a Background on the canvas, it doesn't seem to pay attention to your mouse events.

Try:

<Grid>
    <Canvas Name="canvas"
            MouseMove="canvas_MouseMove"
            MouseLeftButtonUp="canvas_MouseLeftButtonUp"
            Background="White" />
</Grid>
like image 63
Merlyn Morgan-Graham Avatar answered Aug 09 '26 10:08

Merlyn Morgan-Graham