【发布时间】:2019-04-13 13:07:02
【问题描述】:
我有一个创建Label 并显示文本的类。
我还有一个Click 事件,当它触发时,Label 文本会发生变化。
我有另一个类,它将一个方法传递给第一个显示MessageBox的方法。
在主 Form 中,我正在运行一个 for 循环,该循环在随机位置创建该类的 2 个实例。
问题是,当我单击Label 时,Label 上的文本不会改变我想要的。它更改为创建的第一个 Label(类)。
我该如何改变呢?
class J1
{
public Label texto;
public static int a = 0;
//Calls the Method that Creates the Label
public void Spawn(Form form, int _X, int _Y)
{
LL(form, _X, _Y);
}
//Creates the label
public void LL(Form form, int _X, int _Y)
{
texto = new Label()
{
Size = new System.Drawing.Size(35, 50),
Left = _X,
Top = _Y,
Text = "nova label"
};
texto.Click += new EventHandler(Label_Clicada);
form.Controls.Add(texto);
}
void Label_Clicada(object sender, EventArgs e) //Click event when fires
{
J2.M(); //2nd Class that shows a MessageBox
//Changes Text, but doenst change the one that was clicked on
texto.Text = texto.GetType().ToString();
}
}
二等(J2):
class J2
{
public static void M()//Method that I pass to 1nd class(J1)
{
J1.a++;
MessageBox.Show(J1.a.ToString());
}
}
【问题讨论】:
-
在点击事件中使用
(sender as Label).Text = ... -
谢谢伙计,工作就像一个魅力!你能解释一下发件人在这种情况下做了什么吗?为什么它在我的代码中起作用?
-
这意味着
sender也可以是Button或TextBox。全部来自控制。当您必须为具有共同(有意义的)属性的不同控件处理单个事件时,这可能很有用。PictureBox也派生自 Control 并具有Click事件,但Text属性对于该 Control 没有意义。如果是事实,它是隐藏的。但是如果你设置:pictureBox1.Text = "SomeString";,它会被接受的事件,虽然属性没有列出。但是,它不会产生任何效果,因为它对于该控件来说不是有意义的属性(未应用)。
标签: c# winforms class indexing