【问题标题】:How to create a UserControl that you can drop other controls in it?如何创建一个可以将其他控件放入其中的 UserControl?
【发布时间】:2010-11-21 05:55:39
【问题描述】:

在 WinForms 中,我如何创建一个 UserControl,当我放入表单时,我可以通过从工具箱中拖动它们来添加其他控件,与所有容器控件(面板、组框等)的方式相同)?我尝试通过将控件放到我的控件中来添加控件,但是当我移动控件时,我添加的控件保持在它们所在的位置,如果我使用Panel(另一个控件将随面板移动)。

【问题讨论】:

    标签: c# .net winforms user-controls windows-forms-designer


    【解决方案1】:

    例如,与Panel 控件不同,UserControl 在放置在另一个窗体上后不会充当容器控件。在您设计UserControl 本身时,有完整的设计时支持,但它的默认行为不允许它在放置在另一个窗体上后充当构成控件。这就是为什么您无法通过从工具箱中拖动来添加其他控件的原因。

    要将此类行为添加到UserControl,您需要将DesignerAttribute 添加到自定义UserControl 类的定义中。例如:

    using System.ComponentModel;
    using System.ComponentModel.Design;
    
    [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
    public class MyUserControl : System.Windows.Forms.UserControl
    {
        //...your code here
    }
    

    (见相关MSDN文章进一步阅读。)


    如果您想在UserControl 中实现对嵌套 控件的完整设计器支持,这会稍微困难一些。如需更全面的讨论,请参阅 CodeProject 上的this article

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2018-04-29
      • 1970-01-01
      相关资源
      最近更新 更多