查找控件中具有属性的属性
我有一个包含许多控件的页面。
当页面呈现时,我想循环遍历页面上的所有控件,并找到具有特定属性的属性的任何控件。我正在尝试用 c# 来做到这一点 - 有什么想法可以实现这一点吗?
I have a page with a number of controls.
As the page is rendering I want to loop through all controls on the page and find any control that has a property with certain attribute. I am attempting to do this with c# - any ideas how I might achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不知道你的控制树有多大。这就是我要做的。我不保证最好的表现。
案例 1. 查找 .NET 属性
案例 2. 查找 HTML 属性
现在您可以这样调用它:
varcontrolsWAttribute = GetMarkedControls(this.Controls);
从您的页面或任何控件。这样您就不必被迫在页面级别调用它。使用此方法,您可以递归地探索页面或控件中的整个控件树。
I dont know how big is your control tree. This is what I would do. I'm not promissing the best performance.
Case 1. Looking for .NET Attributes
Case 2. Looking for HTML attributes
Now you can call it this way:
var controlsWAttribute = GetMarkedControls(this.Controls);
from your page or any control. This way you are not forced to call it at the page level.With this method you explore the whole control tree in your page or control recursively.
你需要使用反射
http://msdn.microsoft.com/en-us/library/system .reflection.aspx
使用反射可以获取对象的所有属性
You need to use Reflection
http://msdn.microsoft.com/en-us/library/system.reflection.aspx
using reflection you can get all the attributes of an object
页面上的每个控件都有一个“controls”属性,其中包含其所有子控件。我之前已经编写过递归函数来循环这些函数,但手头没有。让我尝试快速写一个:
自从我完成此操作以来已经有一段时间了,我记不清 Collection.Count 是否是一个方法或属性,因此请务必先检查一下,但是如果您传入页面,那么这将检查页面上的每个服务器可见控件,并返回包含与您的比较相匹配的控件的集合。
最后,Control.Attributes 将返回一个 AttributeCollection,您应该能够随后对其进行比较。
Every control that is on the page has a "controls" property which contains all of its children controls. I have written recursive functions to loop through these before but do not have any on hand. Let me try to write one real quick:
Its been a little while since i've done this and I can't remember off the top of my head if Collection.Count is a method or property so make sure you check that first, but if you pass the page in then this will check against every server-visible control on your page and return a collection containing controls that match your comparison.
Lastly, Control.Attributes will return an AttributeCollection which you should be able to subsequently compare against.
不确定你想要什么属性,但如果类属性是你想要的,请查看@user751975,否则你可以做类似的事情......
Not sure what attributes you are after but if class attributes is what you are after look to @user751975 other wise you can do something like ...