如何访问的另一种形式表单控件? [英] How to access a form control for another form?
问题描述
我有两个表格
类,其中之一有一个的ListBox
。我需要为的ListBox
,我想从第二个<$ C $调用的的SelectedIndex
属性的设置C>表格。
I have two Form
classes, one of which has a ListBox
. I need a setter for the SelectedIndex
property of the ListBox
, which I want to call from the second Form
.
目前,我做以下内容:
表格1
public int MyListBoxSelectedIndex
{
set { lsbMyList.SelectedIndex = value; }
}
表格2
private ControlForm mainForm; // form 1
public AddNewObjForm()
{
InitializeComponent();
mainForm = new ControlForm();
}
public void SomeMethod()
{
mainForm.MyListBoxSelectedIndex = -1;
}
这是做到这一点的最好方法是什么?
Is this the best way to do this?
推荐答案
我通常使用Singleton设计模式这样的事情的 http://en.wikipedia.org/wiki/Singleton_pattern 。我会让该应用程序的单身下运行的主要形式,然后创建访问我想要在其他方面碰窗体和控件。然后,其他形式可以得到一个指向他们想要修改的控制,或者他们希望改变应用程序的主要部分的数据。
I usually use the Singleton Design Pattern for something like this http://en.wikipedia.org/wiki/Singleton_pattern . I'll make the main form that the application is running under the singleton, and then create accessors to forms and controls I want to touch in other areas. The other forms can then either get a pointer to the control they want to modify, or the data in the main part of the application they wish to change.
另一种方法是在用于通信的不同的形式设置的事件,并使用主要形式为各种各样的毂以从一种形式的事件消息传递给另一个应用程序中。
Another approach is to setup events on the different forms for communicating, and use the main form as a hub of sorts to pass the event messages from one form to another within the application.
这篇关于如何访问的另一种形式表单控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!