如何自定义PropertyGrid中数组属性的显示文本并保留可展开功能
解决方案
问题原因
你当前自定义的StringViewArrayViewConverter虽然继承了CollectionConverter,但在ConvertTo方法的非匹配分支直接返回了空字符串,覆盖了基类原本用于支持集合展开的核心逻辑,才导致属性无法正常展开。
修正后的实现代码
VB.NET版本
Public Class StringViewArrayViewConverter Inherits CollectionConverter Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object ' 仅当目标类型为字符串、且值是dpStringView数组时,返回自定义摘要 If TypeOf value Is dpStringView() AndAlso destinationType.Equals(GetType(String)) Then Dim arr = CType(value, dpStringView()) Return $"{arr.Length}条消息,展开查看详情" End If ' 其余场景全部调用基类实现,保留集合展开能力 Return MyBase.ConvertTo(context, culture, value, destinationType) End Function ' 显式声明支持属性展开,避免特殊场景下失效 Public Overrides Function GetPropertiesSupported(context As ITypeDescriptorContext) As Boolean Return True End Function Public Overrides Function GetProperties(context As ITypeDescriptorContext, value As Object, attributes() As Attribute) As PropertyDescriptorCollection Return MyBase.GetProperties(context, value, attributes) End Function End Class
属性的应用方式无需修改,和你原有写法一致即可。
C#版本参考
public class StringViewArrayViewConverter : CollectionConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is dpStringView[] arr && destinationType == typeof(string)) { return $"{arr.Length}条消息,展开查看详情"; } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { return base.GetProperties(context, value, attributes); } }
效果说明
修改后PropertyGrid会在属性值列显示你定义的数组摘要文本,同时保留原有展开功能,点击左侧加号即可查看数组内的所有结构体元素。
内容的提问来源于stack exchange,提问作者Bogdan Samchuk
相关产品推荐
相关产品推荐

