在 C# 中,当使用
PropertyGrid
(其中对象具有 Collection
)时,什么决定 DisplayName
旁边的值是否显示 "(Collection)"
的值?
这个值有特定的属性吗?
谢谢
您可以使用类型转换器。
public class MyCollectionTypeConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is List<string>)
{
return string.Join(",", ((List<string>) value).Select(x => x));
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
并添加为属性;
[TypeConverter(typeof(MyCollectionTypeConverter))]
public List<string> Prop1 { get; set; }
参考:如何:实现类型转换器
Kaya 的答案对我不起作用 - 但是 - 我发现当你有任何类型转换器时,属性网格将显示 base.ToString() 而不是 (Collection),我们可以使用它。
public class CollectionToStringOverrideConverter : TypeConverter
{
}
[TypeConverter(typeof(CollectionToStringOverrideConverter))]
public class FormattedList<T> : List<T>
{
public override string ToString()
{
if (this?.Count > 0)
return string.Join("|", this);
return "No items in collection";
}
}
FormattedList 类现在有一个类型转换器,因此使用默认的 ToString(),我们可以在那里放置我们想要的任何内容。只需将您的属性定义为 FormattedList 而不是 List 即可。