在上篇文章(地址: C# 设计时动态改变实体在PropertyGrid中显示出来的属性)中可以看到:
自定义属性的显示是有问题的,那么如何修改呢?
代码如下:
public class PropertyDisplayConverterr<T> : ExpandableObjectConverter where T : IDisplay
{
public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType)
{
if (destinationType == typeof(T))
return true;
return base.CanConvertTo(context, destinationType);
}
// This is a special type converter which will be associated with the T class.
// It converts an T object to string representation for use in a property grid.
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType)
{
if (destinationType == typeof(System.String) && value is T)
{
return ((IDisplay)value).GetDisplayString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
接口:
public interface IDisplay
{
/// <summary>
/// 得到显示字符串
/// </summary>
/// <returns></returns>
string GetDisplayString();
}
修改上文中实体类如下:
[TypeConverterAttribute(typeof(PropertyDisplayConverterr<IdentityColumnEntity>))]
public class IdentityColumnEntity : IDisplay
{
private bool isIncrementColumn;
/// <summary>
/// 是否是自增列
/// </summary>
[Browsable(true)]
[Category("基本")]
[DisplayName("是否是自增列")]
[ReadOnly(false)]
[DefaultValue(false)]
public bool IsIncrementColumn
{
set { isIncrementColumn = value; }
get { return isIncrementColumn; }
}
private Int64 identityIncrement;
/// <summary>
/// 标识增量
/// </summary>
[Browsable(true)]
[Category("基本")]
[DisplayName("标识增量")]
[ReadOnly(false)]
[Description("标识增量属性指定在 Microsoft SQL Server 为插入的行生成标识值时,在现有的最大行标识值基础上所加的值。标识增量必须是 非零 整数,位数等于或小于 10。")]
public Int64 IdentityIncrement
{
set { identityIncrement = value; }
get { return identityIncrement; }
}
private Int64 ident_Seed;
/// <summary>
/// 标识种子
/// </summary>
[Browsable(true)]
[Category("基本")]
[DisplayName("标识种子")]
[ReadOnly(false)]
[Description("指示标识列的初始行值。标识种子必须是 整数,位数等于或小于 10。")]
public Int64 Ident_Seed
{
set { ident_Seed = value; }
get { return ident_Seed; }
}
public string GetDisplayString()
{
if (this == null || this.IdentityIncrement == 0)
{
return "未设置自增列信息";
}
return String.Format("标识种子:{0};标识增量:{1}", this.Ident_Seed, this.IdentityIncrement);
}
}
效果如下:
演示代码:点击打开链接
本文参考:Customized display of collection data in a PropertyGrid
参考文章中demo:点击打开链接
拓展: