在VB.NET中扩展ControlCollection

时间:2020-03-06 14:31:49  来源:igfitidea点击:

我想在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

我在Google上进行了搜索,有人说需要重写CreateControlsInstance方法。所以我做到了,但是随后它给InvalidOperationException加上了一个NullReferenceException的innerException消息。

我该如何实施呢?

解决方案

为什么不继承自UserControl来定义具有诸如Text和Image之类的属性的自定义控件?

无论如何,最好只使用通用集合。 Bieng Control Collection并没有真正为它做任何特别的事情。

puclic class MyCollection : Collection<Control>

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

如果未正确完成此操作,则将在Add方法中引发NullReferenceException。

这也可能导致CreateControlsInstance方法中的InvalidOperationException

以下代码错误地调用了构造函数,导致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