【发布时间】:2011-01-01 14:19:10
【问题描述】:
控件的 Visible 属性的 Get 递归查找树以指示控件是否将被呈现。
我需要一种方法来查看控件的“本地”可见值是什么,而不管其父控件设置为什么。即它本身是否设置为 true 或 false。
我已经看到了这个问题,How to get the “real” value of the Visible property?,它使用反射来获取本地状态,但是,我无法让它在 WebControls 上工作。这也是一种相当肮脏的获取价值的方法。
我想出了以下扩展方法。它的工作原理是从其父控件中移除控件,检查属性,然后将控件放回它找到它的位置。
public static bool LocalVisible(this Control control)
{
//Get a reference to the parent
Control parent = control.Parent;
//Find where in the parent the control is.
int index = parent.Controls.IndexOf(control);
//Remove the control from the parent.
parent.Controls.Remove(control);
//Store the visible state of the control now it has no parent.
bool visible = control.Visible;
//Add the control back where it was in the parent.
parent.Controls.AddAt(index, control);
//Return the stored visible value.
return visible;
}
这是一种可接受的方式吗?它工作正常,我没有遇到任何性能问题。它看起来非常脏,我毫不怀疑它可能会失败(例如,在实际渲染时)。
如果有人对此解决方案有任何想法,或者更好地找到价值的更好方法,那就太好了。
【问题讨论】:
-
您在使用反射方式时遇到了什么问题?
-
GetState 的 GetMethod 为 System.Web.UI.Control 返回 null。
标签: c# .net asp.net web-controls