呼叫另一种形式的仍然是开放的方法? [英] Call method on another form that is still open?

查看:122
本文介绍了呼叫另一种形式的仍然是开放的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有两种形式 - 一个是开放的,另一种是基本上只是在第二个弹出。第二种形式里面一个MaskedTextBox中打开,再加上保存和取消按钮 - 我想保存修改第一个窗体上的字段

So, I have two forms -- one that is open, and another that is essentially just a popup on the second one. The second form opens with a maskedtextbox inside it, plus Save and Cancel buttons -- I want Save to change a field on the first form.

据我所知,我必须用第二种形式为我的弹出,因为我想要完成的任务并不像东西,我可以把在一个消息一样简单 - 如果还有另一种选择,我所有的耳朵。

As far as I know, I have to use a second form for my popup since what I want to accomplish isn't as simple as something I could put in a MessageBox -- if there is another option, I'm all ears.

我一直想:

表格1:

public partial class Form1 : Form
{
   public void ChangeLabel()
   {
       label1.Text = StaticVariables.labelString;
   }
}



表格2:

Form 2:

public partial class Form2 : Form
{
   private void changeForm1_Click(object sender, EventArgs e)
   {
      StaticVariables.labelString = textBox.Text; 
      Form1 frm = new Form1();
      frm.ChangeLabel();
   }
}



显然,这并没有奏效。

Obviously, that hasn't worked.

推荐答案

有没有需要第二种形式了解的第一种形式的。有它知道它的代码的复杂性,并不必要它关系到该表单。有另一种形式寂寂主要形式的内部UI组件更差;如果你这样做,然后改到主窗体显示数据的方式将打破这种其他形式。只要有弹出有代表认为让值的属性就可以设置/获取外部:

There's no need for the second form to know about the first form at all. Having it know about it complicates its code, and needlessly ties it to that form. Having another form knowing about the internal UI components of the main form is even worse; if you do that then changes to how the main form displays the data would break this other form. Just have the popup have a property representing the value that lets it be set/fetched externally:

public partial class Form2 : Form
{
    public string Result //TODO give better name
    {
        get { return textBox.Text; }
    }
    public string DisplayText //TODO give better name
    {
        get { return label.Text; }
        set { label.Text = value; }
    }
}



然后在主窗体可以设置显示值,表现形式,并获取结果值:

Then the main form can set the display value, show the form, and fetch the resulting value:

Form2 popup = new Form2();
popup.DisplayText = "asdf";
popup.ShowDialog();
myField = popup.Result;

这篇关于呼叫另一种形式的仍然是开放的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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