You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET WinForms中UserControl字符串集合属性异常及定义方法

原因分析

  1. 核心设计器特性缺失:注释掉了DesignerSerializationVisibility(DesignerSerializationVisibility.Content)特性,该特性用于告知设计器此属性是可展开编辑的内容属性,需序列化内部元素,缺失后设计器无法正确识别属性的可编辑性。
  2. 自定义集合类结构缺陷:
    • 继承的BaseCollection并非为设计器编辑场景设计,未实现设计器所需的IList等核心接口,设计器无法解析集合结构。
    • 未关联集合编辑器,设计器不知道该用什么组件打开编辑窗口,导致窗口异常关闭。
  3. 集合可编辑性不足:自定义集合仅提供只读索引器,未完整暴露集合的可编辑结构,设计器无法获取足够元数据构建编辑界面。

正确实现方案

方案一:使用.NET自带的StringCollection(推荐)

直接使用System.Collections.Specialized.StringCollection,它内置了设计器支持的所有特性,无需自定义集合:

Imports System.Collections.Specialized
Imports System.ComponentModel
Imports System.Drawing.Design

Private oItems As New StringCollection

<Category("GridBox")>
<DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
<Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design", GetType(UITypeEditor))>
Public Property Items() As StringCollection
    Get
        Return oItems
    End Get
    Set(value As StringCollection)
        oItems = value
    End Set
End Property

方案二:自定义支持设计器的集合类

若需自定义集合,需基于CollectionBase(专为自定义集合设计的基类)实现,并添加必要的设计器特性:

自定义集合类代码

Imports System.Collections
Imports System.ComponentModel

<Serializable()>
Public Class CustomStringCollection
    Inherits CollectionBase

    ' 添加元素
    Public Function Add(item As String) As Integer
        Return List.Add(item)
    End Function

    ' 插入元素
    Public Sub Insert(index As Integer, item As String)
        List.Insert(index, item)
    End Sub

    ' 移除元素
    Public Sub Remove(item As String)
        List.Remove(item)
    End Sub

    ' 可读写索引器
    Default Public Property Item(index As Integer) As String
        Get
            Return CType(List(index), String)
        End Get
        Set(value As String)
            List(index) = value
        End Set
    End Property

    ' 检查元素是否存在
    Public Function Contains(item As String) As Boolean
        Return List.Contains(item)
    End Function

    ' 获取元素索引
    Public Function IndexOf(item As String) As Integer
        Return List.IndexOf(item)
    End Function
End Class

对应的属性定义

Imports System.ComponentModel
Imports System.Drawing.Design

Private oItems As New CustomStringCollection

<Category("GridBox")>
<DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
<Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design", GetType(UITypeEditor))>
Public Property Items() As CustomStringCollection
    Get
        Return oItems
    End Get
    Set(value As CustomStringCollection)
        oItems = value
    End Set
End Property

内容的提问来源于stack exchange,提问作者schlebe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 20:35:33