简体   繁体   中英

Winforms Designer: How to disable my usercontrol from being a container?

I have a relatively simple setup. I have a custom usercontrol that has a bunch of components on it, some text boxes, and a listview.

In the designer, I can drag and drop other controls into my usercontrol, and it adds them to the usercontrol instance. I don't want this.

How can I explicitly say "Don't allow additional controls to be added to this usercontrol?"

再生产

That's not the way it works. When you drop your user control on a form then adding controls to it isn't supported. That requires a special designer, this answer shows what is required. Maybe it looks like the controls get added but they merely overlap your user control. Their parent is still the form.

If a programmer opens your user control class itself in the designer then, sure, he can add controls as he pleases. The only way to stop that is to not ship the source code and use the sealed keyword to prevent deriving from it.

You could create a boolean property MyContainer.DisableAddControls or something.

If your MyContainer.Controls.Add(..) is overridden, then you can throw some custom exception in that Add() method as follows:

if(DisableAddControls)
{
    throw new DisableAddControlsException();
}

If you are inheriting that method straight from ContainerControl , then you can handle the ControlAdded event and throw the exception there.

myContainer.ControlAdded += myContainerControlAdded;

private void Control_Added(object sender, System.Windows.Forms.ControlEventArgs e)
{
    if(DisableAddControls)
    {
        throw new DisableAddControlsException();
    }
}

On second thought, this won't throw out your designer at design time... nevermind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM