简体   繁体   English

创建自定义winforms容器

[英]Create custom winforms container

I want to create a control in winforms with same behavior as the container controls. 我想在winforms中创建一个控件,其行为与容器控件相同。 I mean: in design mode, when I drop controls in it, it will group then, just like a groupbox. 我的意思是:在设计模式下,当我放下控件时,它会分组,就像组合框一样。

This control I'm creating contains some other controls AND a GroupBox. 我正在创建的这个控件包含一些其他控件和一个GroupBox。 All I need is: when a control is droped in design mode over my custom control, I'll just put it inside the nested GroupBox. 我需要的是:当控件在我的自定义控件上以设计模式下垂时,我只是把它放在嵌套的GroupBox中。

But I can't figure out how make my control respond to that kind of action in design mode. 但我无法弄清楚如何让我的控件在设计模式下对这种动作做出反应。

Maybe this is what you need, I found it at CodeProject a time ago: 也许就是你需要的,我在CodeProject上发现它:

Designing Nested Controls: 设计嵌套控件:

This article demonstrates how to allow a Control, which is a child of another Control to accept having controls dropped onto it at design time. 本文演示如何允许控件(另一个控件的子控件)接受在设计时将控件放到其上。 It is not a large article, there is not much by way of code, and this may not be either the 'official' or best way to do this. 这不是一篇大文章,代码方式也不多,这可能不是“官方”或最佳方式。 It does, however, work, and is stable as far as I have been able to test it. 然而,它确实有效,并且只要我能够测试它就是稳定的。

You need to add a Designer attribute to your control, and use a type that derives from or is the ParentControlDesigner Class (needs a reference to the System.Design.dll assembly), like this: 您需要向控件添加Designer属性 ,并使用派生自或是ParentControlDesigner类的类型 (需要对System.Design.dll程序集的引用),如下所示:

[Designer(typeof(MyCustomControlDesigner1))]
public partial class CustomControl1 : Control
{
    public CustomControl1()
    {
        MyBox = new GroupBox();
        InitializeComponent();
        MyBox.Text = "hello world";
        Controls.Add(MyBox);
    }

    public GroupBox MyBox { get; private set; }
}

public class MyCustomControlDesigner1 : ParentControlDesigner
{
    // When a control is parented, tell the parent is the GroupBox, not the control itself
    protected override Control GetParentForComponent(IComponent component)
    {
        CustomControl1 cc = (CustomControl1)Control;
        return cc.MyBox;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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