【问题标题】:Constrain a control's Parent to a particular type in Windows Forms with .NET使用 .NET 将控件的父控件限制为 Windows 窗体中的特定类型
【发布时间】:2013-04-18 14:07:43
【问题描述】:

我想编写一个只能有Form(或派生类)类型的父级的控件。

我猜你可能会将这种行为比作 TabControlTabPage,其中 TabControl 不能有非 TabPage 类型的子代,TabPage 不能有非TabControl.

但是我的实现略有不同,因为与TabControl 不同,我希望我的Form 接受任何类型的控件,但我的控件应该只有Form 类型的父级。

这是我尝试过的:

public class CustomControl : ContainerControl
{
    protected override void OnParentChanged(EventArgs e)
    {
        base.OnParentChanged(e);
        if (!(this.Parent is Form))
        {
            this.Parent.Controls.Remove(this);
            throw new ArgumentException("CustomControl can only be a child of Form");
        }
    }
}

这会在表单设计器中造成一些不良影响,例如:

  1. 尝试在设计器中加载表单时引发异常。
  2. 从表单中删除控件时引发异常。
  3. 控件未正确调整大小。

如果有任何关于如何解决此问题的建议,或者指出我哪里出错了,我将不胜感激。

【问题讨论】:

  • 您从实施此限制中获得了什么价值?
  • @RyanGates,控件改变了窗体的行为,不适用于不是窗体的控件。此外,行为改变不应该在表单级别实现,它应该是一个单独的控件。

标签: c# .net winforms controls


【解决方案1】:

正如人们常说的,最简单的答案往往是最好的……在if 语句中添加一个额外的检查可以解决所有问题! - 傻我!我应该早点尝试的!

public class CustomControl : ContainerControl
{
    protected override void OnParentChanged(EventArgs e)
    {
        base.OnParentChanged(e);
        if (this.Parent != null && !(this.Parent is Form))
        {
            this.Parent.Controls.Remove(this);
            throw new ArgumentException("CustomControl can only be a child of Form");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多