开发者

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 jus开发者_如何学运维t fine.


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>


By not clearing the canvas, but instead moving the preview rectangle in the mouseMove method solved the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜