从WinForms的其他形式的访问公共财产 [英] accessing public property from other form in winforms

查看:134
本文介绍了从WinForms的其他形式的访问公共财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有Form 1和Form。
Form1上具有公共财产

For example I have Form1 and Form2. Form1 has public property

 public IMyCustomType selectedOption;



Form1中组合框自定义对象列表。我想,当用户选择选项从该组合列表selectedOption与价值填充,像

Inside Form1 there is comboBox with custom object list. I want when user select option from that combo list to selectedOption populate with that value, like

public IMyCustomType selectedOption;

private void availableChoices_SelectedIndexChanged(object sender, EventArgs e)
{             
   selectedOption = (IMyCustomType)availableChoices.SelectedItem;                                        
}



窗体2 我要创建所选类型的新实例。如何从窗口2 进入到 selectedOption 属性,并使用该值来创建新的实例?

Inside Form2 I want to create new instance of that selected type. How to access from form2 to that selectedOption property and use that value to create new instance?

推荐答案

如果窗体2从Form1中所示,你可以使用重载用owner参数:

if form2 is shown from form1, you may use overload with owner parameter:

form2.Show(form1);



然后在窗口2,你简单的把它从主人属性:

then in form2 you simple take it from owner property:

((Form1)this.Owner).selectedOption

或者您可以了解创建的窗体2公开的方法,将接受所选选项作为参数,并显示窗体2之前调用它。

Or alternatively you can craete public method in form2, that would accept selected option as parameter and call it before showing form2.

public class Form2 : Form {
  private IMyCustomType parentSelectedOption;
  ...
  public void InitParameters(IMyCustomType selectedOption) 
  {
      parentSelectedOption = selectedOption;
  }
}

public class Form1 : Form {
     ....
     var form2 = new Form2();
     form2.InitParameters(selectedOption);
     form2.Show();
}



心灵的命名虽然,公共属性(在你的情况下,它是场)通常使用驼峰而得名。

Mind naming though, public properties (in your case it is field) are usually named using CamelCase.

这篇关于从WinForms的其他形式的访问公共财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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