访问Windows窗体其他窗体上的控件的最佳方式? [英] Best way to access a control on another form in Windows Forms?

查看:111
本文介绍了访问Windows窗体其他窗体上的控件的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是一个有关使用Windows窗体,而不是一个 ASP.NET 问题的桌面应用程序的问题

First off, this is a question about a desktop application using Windows Forms, not an ASP.NET question.

我需要与其他形式的控件进行交互。我试图通过使用访问控制,例如,下面...

I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...

otherForm.Controls["nameOfControl"].Visible = false;

它不工作,我希望的方式。我最终从抛出的异常。不过,如果我使控件公共而不是私人,然后我就可以直接访问它们,如此...

It doesn't work the way I would expect. I end up with an exception thrown from Main. However, if I make the controls public instead of private, I can then access them directly, as so...

otherForm.nameOfControl.Visible = false;

但是,这是最好的方式做到这一点?被认为是最佳做法的其他形式的决策上的控件公共?是否有一个更好的方式来访问另一个窗体上的控件?

But is that the best way to do it? Is making the controls public on the other form considered "best practice"? Is there a "better" way to access controls on another form?

进一步的解释:

这其实是一种后续的另一个问题,我问,的 Best在C#中建立一个树视图preferences对话框中的类型的接口的方法是什么? 的。我得到的答案是伟大的,我解决了在保持UI直,易于使用无论是在运行时和设计时工作方面有很多很多的组织问题。然而,它也带来了这一个琐碎的容易控制接口的其他方面的问题。

This is actually a sort of follow-up to another question I asked, Best method for creating a "tree-view preferences dialog" type of interface in C#?. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.

基本上,我有一个实例很多其他形式的坐根窗体上的面板根形式。因此,例如,对那些子形式之一的无线电按钮可能需要改变主,根形态上的状态条图标的状态。在这种情况下,我需要分形式去跟在父(根)表单的状态条上的控制。 (我希望是有道理的,而不是在谁是第一次的一种方式。)

Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)

推荐答案

而不是使控制公众,你可以创建一个控制其可见性属性:

Instead of making the control public, you can create a property that controls its visibility:

public bool ControlIsVisible
{
     get { return control.Visible; }
     set { control.Visible = value; }
}

这将创建一个适当的访问到控制,不会暴露控制的一整套属性。

This creates a proper accessor to that control that won't expose the control's whole set of properties.

这篇关于访问Windows窗体其他窗体上的控件的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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