如何将rectenge从一个事件函数传递给另一个事件函数? [英] how to pass rectenge from one event function to another?

查看:105
本文介绍了如何将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;
        }
                
        }


这篇关于如何将rectenge从一个事件函数传递给另一个事件函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆