按名称在 Windows 窗体中查找控件 [英] Find a control in Windows Forms by name

查看:38
本文介绍了按名称在 Windows 窗体中查找控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个在运行时添加对象(基本上是 Windows Forms 控件)的应用程序来自一个 XML 文件.应用程序需要访问已添加的对象.

I am working on an application which add objects (basically Windows Forms controls) at run time from an XML file. The application needs to access the objects that have been added.

对象被添加到面板或分组框中.对于面板和分组框,我有 Panel.Controls["object_name"] 来访问对象.这仅在对象直接添加到同一面板上时才有用.在我的例子中,主面板 [pnlMain,我只能访问这个面板] 可能包含另一个面板,这个面板 [pnlChild] 再次包含一个 groupbox[gbPnlChild] 并且 groupbox 包含一个按钮 [button1,我想访问这个按钮].我有以下方法:

The objects are added in a panel or in a groupbox. For the panel and groupbox, I have Panel.Controls["object_name"] to access the objects. This is only helpful when the object is directly added on the same panel. In my case the main panel [pnlMain, I have access to this panel only] may contain another panel and this panel [pnlChild] again contains a groupbox[gbPnlChild] and the groupbox contains a button [button1, I want to access this button]. I have the following method for this:

Panel childPanel = pnlMain.Controls["pnlChild"];
GroupBox childGP = childPanel.Controls["gbPnlChild"];
Button buttonToAccess = childGP["button1"];

当父母知道时,上述方法很有帮助.在我的场景中,只知道要访问的对象的名称 [button1] 而不是其父对象.那么我如何通过它的名称访问这个对象,而与它的父对象无关?

The above method is helpful when parents are known. In my scenario, only the name of the object is known that is to be accessed [button1] and not its parents. So how do I access this object by its name, irrelevant of its parent?

有像 GetObject("objName") 或类似的方法吗?

Is there a method like GetObject("objName") or something similar?

推荐答案

您可以使用表单的 Controls.Find() 方法来检索引用:

You can use the form's Controls.Find() method to retrieve a reference back:

        var matches = this.Controls.Find("button2", true);

请注意,这会返回一个数组,控件的 Name 属性可能不明确,没有机制可以确保控件具有唯一的名称.你必须自己强制执行.

Beware that this returns an array, the Name property of a control can be ambiguous, there is no mechanism that ensures that a control has a unique name. You'll have to enforce that yourself.

这篇关于按名称在 Windows 窗体中查找控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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