在实例类之间传递静态值

时间:2017-03-31 06:05:54

标签: c# winforms

我有两个表单(form1和form2),它们实例化包含按钮和标签的新类的两个对象。我希望当一个实例中的文本标签更改时,两个实例都使用新文本''刷新''

Form1中:

public partial class Form1 : Form
{
    thisclassobjectform newclassform1;
     public Form1()
    {
        InitializeComponent();
        newclassform1 = new thisclassobjectform();
        this.Controls.Add(newclassform1.BasePanel);
        newclassform1.BasePanel.Location = new Point(1, 1);
        Form2 newForm = new Form2();
        newForm.Show();
    }
}

新课程:

public class thisclassobjectform
{
    public Panel BasePanel;
    Button newbutton;
    Label Textinit;
    static int i = 2;
    static string txtstring;

   // public static event EventHandler neweventvaluevchange;//with event
  //  public delegate void newdelegatevaluechange(object sender, EventArgs e);//with event
    public delegate void newdelegatevaluechange();//with delegate
    static newdelegatevaluechange thisdelegate;//with delegate
    public thisclassobjectform()//ctor
    {
        BasePanel = new Panel();
        newbutton = new Button();
        newbutton.Text = "click me";
        newbutton.Location = new Point(2, 2);
        Textinit = new Label();
        Textinit.Text = "one label text";
        Textinit.AutoSize = true;
        Textinit.Location = new Point(2, 40);
        BasePanel.Controls.Add(newbutton);
        BasePanel.Controls.Add(Textinit);
        newbutton.Click +=new EventHandler(newbutton_Click);
       // neweventvaluevchange+=new EventHandler(thisclassobjectform_neweventvaluevchange);//with event
        thisdelegate += new newdelegatevaluechange(thisclassobjectform_neweventvaluevchange);//with delegate
    }
    private void newbutton_Click(object sender, EventArgs e)
    {
        txtstring = ("some text has changed" + (i++).ToString());
        thisdelegate();//with delegate
        //neweventvaluevchange(this, EventArgs.Empty);//with event
    }
    //private void thisclassobjectform_neweventvaluevchange(object sender, EventArgs e)//with event
    private void thisclassobjectform_neweventvaluevchange()//with delegate
    { Textinit.Text = txtstring; }
}

窗体2:

 public partial class Form2 : Form
  {
   thisclassobjectform newclassform2;

    public Form2()
    {
        InitializeComponent();
        newclassform2 = new thisclassobjectform();
        this.Controls.Add(newclassform2.BasePanel);
        newclassform2.BasePanel.Location = new Point(1, 1);
    }
}

我可以使用event(或/和)委托(它是相同的)来做到这一点......但是我可以用另一种方式做得更干净吗?

0 个答案:

没有答案