c# - 覆盖 Control.ControlCollection 的正确方法

标签 c# winforms user-controls

我着手创建一个自定义 TabControl 小部件,以便我可以在选项卡的右边缘用关闭的 X 准确地绘制选项卡。我有一个包含所有选项卡的自定义数组类。

所以我覆盖了 CreateControlsInstance 实例类并重新定义了 Controls 类,这样我就可以在反射序列化期间隐藏它。

protected override Control.ControlCollection CreateControlsInstance() {
  return new ControlCollection( this );
}

[Browsable( false ), DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )]
private new Control.ControlCollection Controls {
  get { return base.Controls; }
}

然后我创建覆盖类。

public new class ControlCollection: Control.ControlCollection {
  private xTabControl owner;

  public ControlCollection( xTabControl owner ): base( owner ) {
    this.owner = owner;
  }

  public override void Add( Control value ) {
    if ( !(value is xTabPage) )
      throw new Exception( "The control must be of type xTabPage" );

    xTabPage tabPage = (xTabPage)value;

    if ( !owner.inTabEvent )
      owner._tabPages.Add( tabPage );

    base.Add( value );
  }

  public override void Remove( Control value ) {
    if ( !(value is xTabPage) )
      throw new Exception( "The control must be of type JDMX.Widget.xTabPage" );

    if ( !owner.inTabEvent ) {
      xTabPage tabPage = (xTabPage)value;
      owner._tabPages.Remove( tabPage );
    }

    base.Remove( value );
  }

  public override void Clear() {
    owner._tabPages.Clear();
  }
}

目前这是可行的,但如果 Controls 类仍然可以调用方法 SetChildIndex 等,这会更改底层数组列表而不是 tabPages 数组。

我希望能够消除新的 ControlCollection 类必须使用基类来向 xTabControl 注册新的 xTabPage 对象的需要。

我已经使用 .Net Reflector 完成了类结构。我希望不必复制一半的 Control 类来注册新的小部件。

我知道这是不可能的,但有人成功过吗?

最佳答案

在我的整个研究过程中,由于将控件分配给 Add 函数所提供的函数数量众多,因此我找不到不使用 System.Windows.Forms.Control.ControlCollection 就可以管理 UserControl 的实例。当我开始将 Designer 纳入等式时,情况更糟。所以我决定使用上面给出的自定义覆盖来接受 Controls 属性。我现在需要使我的私有(private)级别 _tabPages 与控件集合保持同步,而不是相反。

关于c# - 覆盖 Control.ControlCollection 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2315475/

相关文章:

c# - 如何在 Xamarin.iOS 应用程序中创建导航?

asp.net - 使用 jQuery 将 ASP.NET 控件添加到页面

javascript - GridView 中自动完成用户控件的 SelectedValue 属性

c# - ExtractAssociatedIcon 在 ListView 中显示质量较差的图标

c# - 如何在要打印的收据上添加选定的 ListBox 项目及其价格?

c# - 如何使用 Bing map 检索邮政地址的纬度和经度?

javascript无法从文本框中获取字符串

Java 与 C# : Java and C# subclasses with method overrides output different results in same scenario

c# - Microsoft ReportViewer 2012 引用

c# - XAML 框架从未针对表单行为调用 OnDetachingForm