老师,你好!
我在Form1使用了一个butonn和一个label1控件,但我想在另一个类中改写label1控件的标题,怎样才能实现?
namespace WindowsApplication18
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
text a= new text();
a.money();
}
}
public class text
{
public void money()
{
label1.Text = "123";
}
}
}
我在Form1使用了一个butonn和一个label1控件,但我想在另一个类中改写label1控件的标题,怎样才能实现?
namespace WindowsApplication18
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
text a= new text();
a.money();
}
}
public class text
{
public void money()
{
label1.Text = "123";
}
}
}
{
set{ label1.Text = value;}
}
最简单的办法,找到Form1.designer.cs修改Label1的修饰符由private改为protected
第二种方法
给Form1一个公开的属性返回Label1.Text,从而可以在Form2中访问此属性
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
text a = new text();
a.Changed += new EventHandler<TextEventArgs>(a_Changed);
a.money();
} void a_Changed(object sender, TextEventArgs e)
{
label1.Text = e.TextValue;
}
}
public class TextEventArgs : EventArgs
{
private string m_TextValue;
public TextEventArgs(string textValue)
{
this.m_TextValue = textValue;
}
public string TextValue
{
get { return m_TextValue; }
set { m_TextValue = value; }
}
}
public class text
{
public event EventHandler<TextEventArgs> Changed;
public void money()
{
if (Changed != null)
{
TextEventArgs args = new TextEventArgs("123");
Changed(this, args);
}
}
}
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
text a = new text(label1);
a.money();
}
}
public class text
{
Label pLab;
public text(Label lab)
{
pLab = lab;
}
public void money()
{
pLab.Text = "123";
}
}
设置一个属性用来修改label的textpublic string LabelText
{
set{ label1.Text = value;}
}
操作不就行了
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
text a= new text();
a.money(label1);
}
}
public class text
{
public void money(Label displayLabel)
{
displayLabel.Text = "123";
}
}
}
public class text
{
public void money(ref Label displayLabel)
{
displayLabel.Text = "123";
}
}