我的用户控件应该只添加到某种类型的控件

My user control should only be added to a certain type of control

如何才能让我的用户控件只能添加到某种类型的控件中(在我这里,具体是SplitContainer)?

您需要注意几件事:

  1. 控件的工具箱项行为
  2. 控件的设计器行为
  3. 控件的运行时间运行时间行为(可选)

当您将控件从工具箱放到设计图面上时,您应该防止它被放到不需要的控件上;这是 CreateComponents method of the ToolBoxItem class 分配给控件的责任。

将控件添加到设计表面后(例如在所需的父级中),然后您需要防止将其拖到不需要的控件上;这是 CanBeParentedTo method of the ControlDesigner class 分配给控件的责任。

最后,您甚至可能想在 运行 时阻止以编程方式将其添加到不需要的控件中;在这种情况下,它是控件的 OnParentChanged 方法的责任。

示例 - 限制控件仅托管在 SplitterContainer

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolboxItem(typeof(MyControlToolBoxItem))]
[Designer(typeof(MyControlDesigner))]
public class MyControl : Control
{
    protected override void OnParentChanged(EventArgs e)
    {
        if (Parent != null && !(Parent is SplitterPanel))
            throw new Exception("You can add this control only to a SplitterContainer.");
        base.OnParentChanged(e);
    }
}
public class MyControlDesigner : ControlDesigner
{
    public override bool CanBeParentedTo(IDesigner parentDesigner)
    {
        if (parentDesigner.Component is SplitterPanel)
            return true;
        else
            return false;
    }
}
public class MyControlToolBoxItem : ToolboxItem
{
    protected override IComponent[] CreateComponentsCore(IDesignerHost host,
        System.Collections.IDictionary defaultValues)
    {
        if (defaultValues.Contains("Parent"))
        {
            var parent = defaultValues["Parent"];
            if (parent != null && parent is SplitterPanel)
                return base.CreateComponentsCore(host, defaultValues);
        }
        var svc = (IUIService)host.GetService(typeof(IUIService));
        if (svc != null) 
            svc.ShowError("You can drop this control only over a SplitterContainer.");
        return null;
    }
}