如何以编程方式处理Canvas事件WPF

本文关键字:Canvas 事件 WPF 处理 方式 编程 | 更新日期: 2023-09-27 17:58:48

我在代码背后自动绘制了几个画布。那么我如何处理每个画布的事件呢?

将画布添加到堆栈面板,并尝试将处理程序添加到每个画布:

 for (int i = 0; i < canvases.Count; i++)
 {
     canvases[i] = new Canvas();
     canvases[i].Width = sheetWidth;
     canvases[i].Height = sheetHeight;
     canvases[i].Background = Brushes.White;
     canvases[i].MouseWheel += new MouseWheelEventHandler((object sender,MouseWheelEventArgs e) =>
     {
          double ScaleRate = 1.00000001;
          ScaleTransform scaletransform = new ScaleTransform();
          if (e.Delta > 0)
          {
              scaletransform.ScaleX *= ScaleRate;
              scaletransform.ScaleY *= ScaleRate;
          }
          else
          {
              scaletransform.ScaleX /= ScaleRate;
              scaletransform.ScaleY /= ScaleRate;
          }
          canvases[i].RenderTransform = scaletransform;
    });
    stackPanel.Children.Add(canvases[i]);
 }

以这种形式抛出System.IndexOutOfRangeException,当我试图移动鼠标滚轮时。。。

如何以编程方式处理Canvas事件WPF

尝试这样更改代码:

for (int i = 0; i < canvases.Count; i++)
{
    canvases[i] = new Canvas();
    canvases[i].Width = sheetWidth;
    canvases[i].Height = sheetHeight;
    canvases[i].Background = Brushes.White;
    canvases[i].RenderTransform = new ScaleTransform(); // here !!!
    canvases[i].MouseWheel += (sender, e) =>
    {
        double ScaleRate = 1.00000001; // really ??
        var canvas = (Canvas)sender;
        var scaletransform = (ScaleTransform)canvas.RenderTransform;
        if (e.Delta > 0)
        {
            scaletransform.ScaleX *= ScaleRate;
            scaletransform.ScaleY *= ScaleRate;
        }
        else
        {
            scaletransform.ScaleX /= ScaleRate;
            scaletransform.ScaleY /= ScaleRate;
        }
   };
   stackPanel.Children.Add(canvases[i]);

}