Windows窗体的FindControl(译文)
By S.F.
本文链接 https://www.kyfws.com/news/findcontrol-for-windows-forms/
版权声明 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
- 2 分钟阅读 - 522 个词 阅读量 0Windows窗体的FindControl(译文)
原文地址:https://www.codeproject.com/Articles/44928/FindControl-for-Windows-Forms
原文作者:Joel Ivory Johnson
译文由本站翻译
前言
Windows窗体的FindControl的快速实现.
有人在Windows Mobile编程论坛中提出了一个问题.运行时控制.当我看到这个问题时,想到的第一个解决方案是" Control.FindControl".在我建议使用该方法之前,我搜索了MSDN文档,发现它仅存在于ASP.NET中. Windows Forms完全缺少它.因此,我整理了该功能的快速实现.
Control FindControl(string target )
{
return FindControl(this, target);
}
static Control FindControl(Control root, string target)
{
if(root.Name.Equals(target))
return root;
for(var i=0;i<root.Controls.Count;++i)
{
if (root.Controls[i].Name.Equals(target))
return root.Controls[i];
}
for(var i=0;i<root.Controls.Count;++i)
{
Control result;
for(var k=0;k<root.Controls[i].Controls.Count;++k)
{
result = FindControl(root.Controls[i].Controls[k], target);
if(result!=null)
return result;
}
}
return null;
}
要使用该功能,只需在需要该功能的表单的根部定义它.如果不能在根窗体上定义它,则可以使用它的静态版本,将对要在其中搜索的控件层次结构的容器的引用传递给该方法.该函数将递归搜索控件层次结构,直到找到具有指定名称的UI对象为止;否则,如果找不到该对象,则返回" null".
许可
本文以及所有相关的源代码和文件均已获得The Code Project Open License (CPOL)的许可。
C# Windows .NET Dev Beginner 新闻 翻译