我想将一个矩形从一个Event函数传递给另一个Event函数 [英] I want to to pass a rectangle from one Event function to a second Event function
本文介绍了我想将一个矩形从一个Event函数传递给另一个Event函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将矩形从一个函数传递给第二个函数
由于某种原因,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;
}
推荐答案
A几点需要注意。首先是私人矩形矩形;和Rectangle rect = new Rectangle();将成为两个对象,第二个对象只是方法canvas1_MouseRightButtonDown。要解决这个问题,请删除第二个中的对象标识符,使其为rect = new Rectangle();。
第二个构建第一个,因为你需要在调用MouseMove事件之前初始化对象。两种想法取决于C#的版本。将初始化放在方法之外:
private Rectangle rect = new Rectangle();
在版本4+中,我们在Java中也做了一些内部方法,类似于:
Rectangle rect = new Rectangle(){
Stroke = Brushes.Black;
StrokeThickness = 1;
}
但是,一旦创建了对象,如果需要,可以在两种方法中重做Rectangle的某些特征。
A couple of things to note. The first is, "private Rectangle rect;" and "Rectangle rect = new Rectangle();" are going to be two objects, with the second being local only to the method "canvas1_MouseRightButtonDown". To rectify this, remove the object identifier in the second so it is "rect = new Rectangle();".
The second builds off the first in that you need to have the object initialized before the "MouseMove" event is called. Two thoughts depending upon the version of C#. Put the initialization outside of the methods:
private Rectangle rect = new Rectangle();
In version 4+ there is also something we do in Java to be an inner method, something like:
Rectangle rect = new Rectangle(){
Stroke = Brushes.Black;
StrokeThickness = 1;
}
however, once you have your object created, you can "redo" certain characteristics of the Rectangle in both methods if need be.
这篇关于我想将一个矩形从一个Event函数传递给另一个Event函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文