您应该为您的整数属性实现自定义type converter:
class MyData
{
[TypeConverter(typeof(CustomNumberTypeConverter))]
public int MyProp { get; set; }
}
PropertyGrid 使用 TypeConverter 将您的对象类型(在本例中为整数)转换为字符串,用于在网格中显示对象值。在编辑过程中,TypeConverter 会从字符串转换回您的对象类型。
因此,您需要使用类型转换器,它应该能够将整数转换为带有千位分隔符的字符串,并将此类字符串解析回整数:
public class CustomNumberTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string)
{
string s = (string)value;
return Int32.Parse(s, NumberStyles.AllowThousands, culture);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
return ((int)value).ToString("N0", culture);
return base.ConvertTo(context, culture, value, destinationType);
}
}
结果:
propertyGrid.SelectedObject = new MyData { MyProp = 12345678 };
我推荐你阅读Getting the Most Out of the .NET Framework PropertyGrid Control
MSDN 文章了解 PropertyGrid 的工作原理以及如何对其进行自定义。