Canvas 鼠标事件在 wpf 中不起作用

Canvas mouse events don't work wpf

我有以下 ObservableCollection:`

private ObservableCollection<Grid> m_streams = new ObservableCollection<Grid>();

public ObservableCollection<Grid> Streams
{
    get { return m_streams; }
    set
    {
        m_streams = value;
        OnPropertyChanged();
    }
}

我还有一个 Command,它在 Streams 的列表中添加了一个带有 Canvas 的新 Grid:

private void AddCanvas(object parameter)
{
    var newGrid = new Grid { Name = "Grid_No_" + Streams.Count + 1 };
    var newCanvas = new Canvas { Name = "Canvas_No_" + Streams.Count + 1, Background = Brushes.Cyan};

    newCanvas.MouseDown += MouseClick;
    newCanvas.MouseMove += MouseMove;
    newCanvas.MouseUp += MouseClick;

    newGrid.Children.Add(newCanvas);

    Streams.Add(newGrid);
}

最后,我有以下 MouseClick 事件函数:

private static void MouseClick(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
      MessageBox.Show("Working");
}

这个流程完美无缺。

但是,如果我通过将 Image 添加到 Grid 来更改 AddStream 函数,如下所示:

private void AddCanvas(object parameter)
{
    var newGrid = new Grid { Name = "Grid_No_" + Streams.Count + 1 };
    var newCanvas = new Canvas { Name = "Canvas_No_" + Streams.Count + 1 };
    var newImage = new Image { Name = "Image_No_" + Streams.Count + 1, Source = new BitmapImage(new Uri(@"C:\SomeImage.jpg")) };

    newCanvas.MouseDown += MouseClick;
    newCanvas.MouseMove += MouseMove;
    newCanvas.MouseUp += MouseClick;

    newGrid.Children.Add(newImage);
    newGrid.Children.Add(newCanvas);

    Streams.Add(newGrid);
}

然后,Image 按预期显示,但是当我单击 Canvas 上的任意位置时不再调用 MouseClick 函数。

我在这里错过了什么?

您的 canvas 必须将 Background 设置为 Brushes.Transparent 才能使命中测试正常工作。