使用模式按名称查找 Windows 窗体控件 [英] Find Windows Forms control by name using a pattern

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

问题描述

我想列出另一个控件中名称以btnOverlay"开头的所有控件.我不能使用 Controls.Find,因为它需要完全匹配.我相信我可以为此使用 LINQ,但我对此不是很有经验.是否可以?我该怎么做?

I want to list all controls inside another control which have names starting with "btnOverlay". I can't use Controls.Find, because it needs an exact match. I believe I can use LINQ for this, but I'm not very experienced on that. Is it possible? How can I do it?

我使用的是 .NET 4.0.

I'm using .NET 4.0.

推荐答案

您可以通过以下方式使用 LINQ 搜索它们:

You could search for them with LINQ via:

var matches = control.Controls.Cast<Control>()
                     .Where(c => c.Name.StartsWith("btnOverlay"));

Cast 调用是必需的,因为 ControlCollection 没有实现 IEnumerable,只有 IEnumerable代码>.此外,这不会进行递归搜索,而只会直接搜索包含的控件.如果需要递归,您可能需要将其重构为 类似于这个答案的方法.

The Cast<T> call is required, as ControlCollection does not implement IEnumerable<T>, only IEnumerable. Also, this doesn't do a recursive search, but only searches the contained controls directly. If recursion is required, you'll likely need to refactor this into a method similar to this answer.

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

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