在VB.NET中扩展ControlCollection

问题描述:

我想在VB.NET中扩展基本ControlCollection,这样我就可以将图像和文本添加到自制控件中,然后自动将它们转换为pictureboxes和lables。在VB.NET中扩展ControlCollection

所以我做了一个继承自ControlCollection的类,重写了add方法,并添加了功能。

但是当我运行这个例子时,它给出了一个NullReferenceException

下面是代码:

 Shadows Sub add(ByVal text As String) 
      Dim LB As New Label 
      LB.AutoSize = True 
      LB.Text = text 
      MyBase.Add(LB) 'Here it gives the exception. 
     End Sub 

我搜索在谷歌,有人说,CreateControlsInstance方法需要被重写。所以我这样做了,但是它给InvalidOperationException发送innerException消息NullReferenceException

我该如何执行此操作?

为什么不从UserControl继承来定义一个自定义控件,该控件具有像Text和Image这样的属性?

无论如何,您可能最好只使用泛型集合。 Bieng Control Collection不会为它做任何特别的事情。

puclic class MyCollection : Collection<Control> 

如果你是从Control.ControlCollection继承,那么你需要在你的类中提供一个New方法。您的新方法必须调用ControlCollection的构造函数(MyBase.New)并将其传递给一个有效的父控件。

如果你没有正确地做到这一点,NullReferenceException将在Add方法中抛出。

这也可能导致出现InvalidOperationException在CreateControlsInstance方法

下面的代码调用构造函数不正确造成的Add方法抛出一个NullReferenceException ...

Public Class MyControlCollection 
    Inherits Control.ControlCollection 

    Sub New() 
     'Bad - you need to pass a valid control instance 
     'to the constructor 
     MyBase.New(Nothing) 
    End Sub 

    Public Shadows Sub Add(ByVal text As String) 
     Dim LB As New Label() 
     LB.AutoSize = True 
     LB.Text = text 
     'The next line will throw a NullReferenceException 
     MyBase.Add(LB) 
    End Sub 
End Class