查找Windows窗体的名字控制 [英] Find a control in Windows Forms by name

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

问题描述

我的工作里面添加对象的应用程序(基本上 Windows窗体控件)在运行时从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]又包含了组框[gbPnlChild]和组框包含一个按钮[按钮1,我要访问此按钮] 。我对这个下面的方法:

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);

要注意的是这个返回的阵列的,控件的名称属性可以是模糊的,没有机制可确保控件具有唯一的名称。你必须强制自己。

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天全站免登陆