问题描述
首先,这是关于使用 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;
它不像我期望的那样工作.我最终从 Main
抛出异常.但是,如果我将控件设为 public
而不是 private
,那么我就可以直接访问它们,因此...
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;
但这是最好的方法吗?是否将另一种形式的控件 public
视为最佳实践"?是否有更好"的方式来访问另一个表单上的控件?
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?
进一步说明:
这实际上是对我问的另一个问题的一种跟进,在 C# 中创建树视图首选项对话框"类型界面的最佳方法?.我得到的答案很好,解决了我在保持 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 窗体中访问另一个窗体上的控件的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!