为什么我的WPF应用中的Canvas上的MouseLeftButtonUp无法启动?
这是XAML:

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


和代码:

    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;
    }


编辑:我曾尝试向画布添加背景色,但仍未触发该事件。似乎MouseMove会以某种方式覆盖MouseLeftButtonUp。

Edit2:如果删除MouseMove事件,将触发mouseLeftButtonUp。

Edit3:更大的代码示例。
       在insertRectangle方法中,如果我使用

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


事件触发得很好。

最佳答案

如果您未在画布上设置Background,则它似乎并不会关注您的鼠标事件。

尝试:

<Grid>
    <Canvas Name="canvas"
            MouseMove="canvas_MouseMove"
            MouseLeftButtonUp="canvas_MouseLeftButtonUp"
            Background="White" />
</Grid>

09-06 00:15