如何将rectenge从一个事件函数传递给另一个事件函数?

如何将rectenge从一个事件函数传递给另一个事件函数?

问题描述:

我想将矩形从一个函数传递给第二个函数

由于某种原因,rectangel读取事件函数为null

我该怎么做?







I want to to pass a rectangle from one function to a second function
For some reason the rectangel read to the event function as null
How can I do this?



      private Point startpoint;
      private Rectangle rect;

      private void canvas1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
      {

          startpoint = Mouse.GetPosition(canvas1);

// the rectengle that i creat and i what to pass him to the canvas1_MouseMove Event function
          Rectangle rect = new Rectangle();
          rect.Stroke = Brushes.Black;
          rect.StrokeThickness = 1;


          canvas1.Children.Add(rect);



      }



      private void canvas1_MouseMove(object sender, MouseEventArgs e)
      {
         //to here i want to pass the rectangle
         // when i debug the code the rect value is null!
         // so i cant control his Properties


              rect.Width = 5;// her i got excsption
                             //"Object reference not set to an instance of an object."
              rect.Height = 6;





      }

这是最简单的方法。



This is the simplest way to do it.

        private Point startpoint;

// "rect" is declared at Class level so both canvas1_MouseRightButtonDown and canvas1_MouseMove can access
        private Rectangle rect; 
 
        private void canvas1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            startpoint = Mouse.GetPosition(canvas1);
 
            rect = new Rectangle();  // Changed declaration and assignment to just assignment
            rect.Stroke = Brushes.Black;
            rect.StrokeThickness = 1;
 
            canvas1.Children.Add(rect);
         }
 
        
 
        private void canvas1_MouseMove(object sender, MouseEventArgs e)
        {
        if (rect != null) // Check to be sure rect is OK. Mouse will move before right-click.
        {
                 rect.Width = 5;
                rect.Height = 6;
        }
                
        }