问题
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?
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
is of type Control
and in my testing is either Combox
or GroupBox
.
In both cases the GetCustomAttributes
returns an array of 1 attribute which is the toolbox icon.
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?
回答1:
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 });
}
来源:https://stackoverflow.com/questions/21704752/determine-at-run-time-if-a-control-allows-other-controls-to-be-added-to-it-at-de