在运行时确定控件是否允许在设计时向其添加其他控件 [英] Determine at run time if a control allows other controls to be added to it at design time
问题描述
我需要操纵表单上的所有控件。我可以访问Controls集合来做到这一点。问题在于试图包含容器控件中包含的所有控件,例如 GroupBox
或 Panel
。我可以递归地迭代每个Control自己的Controls集合,但这随后将访问所有非设计时间容器的构成控件。
I need to manipulate all controls on a form. I'm fine with accessing the Controls collection to do this. The problem comes with trying to include any controls contained within container controls such of GroupBox
or Panel
. I could recursively iterate the each Control's own Controls collection but this then accesses all constituent controls for non-design time containers.
由于我的非容器控件均管理其构成控件'根据自己的属性声明状态,我不会开始弄乱组成控件。
Since my non-container controls all manage their constituent controls' state based on the their own properties I don't to start messing with constituent controls.
如何确定控件是否是设计时间容器,以便我可以避免处理那些不是?
How can I determine if a control is a design time container so that I can avoid process those that are not?
我尝试检查Designer属性,但这对于 ComboBox $ c $都返回null c>和
GroupBox
:
I've tried checking for the Designer attribute but this returns null for both the ComboBox
and the GroupBox
:
foreach(Attribute attr in typeof(ctl).GetCustomAttributes(typeof(Attribute), false))
{
if(typeof(DesignerAttribute).IsAssignableFrom(attr.GetType()))
{
DesignerAttribute da = (DesignerAttribute)attr;
}
}
ctl
的类型为 Control
,在我的测试中为 Combox
或 GroupBox
。
ctl
is of type Control
and in my testing is either Combox
or GroupBox
.
在两种情况下, GetCustomAttributes
返回的数组都是1个属性,即工具箱图标
In both cases the GetCustomAttributes
returns an array of 1 attribute which is the toolbox icon.
我也尝试检查从 ContainerControl
类的可分配性,但是它们都是因为,我认为,它们都将在运行时包含控件。
I've also tried checking assignability from to the ContainerControl
class but they both are because, I assume, they will both contain controls at run time.
如何检测设计时间容器?
How do I detect a design time container?
推荐答案
在如果Hans不回来,并且有人感兴趣,这是我根据Hans Passant的建议解决问题的方法:
In case Hans doesn't come back, and anyone is interested, this is my solution to the problem based on Hans Passant's suggestion:
public static bool IsContainerControl(this Control ctl)
{
if (ctl == null)
return false;
MethodInfo GetStyle = ctl.GetType().GetMethod("GetStyle", BindingFlags.NonPublic | BindingFlags.Instance);
if (GetStyle == null)
return false;
return (bool)GetStyle.Invoke(ctl, new object[] { ControlStyles.ContainerControl });
}
这篇关于在运行时确定控件是否允许在设计时向其添加其他控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!