属性网格数格式

是否可以格式化winforms的PropertyGrid中显示的数字属性?

class MyData { public int MyProp {get; set;} } 

我希望它在网格中显示为例如1.000.000。

这有什么属性吗?

您应该为整数属性实现自定义类型转换器 :

 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 }; 

在此处输入图像描述

我建议您阅读“ 充分利用.NET Framework PropertyGrid控件 MSDN”一文,了解PropertyGrid的工作原理以及如何自定义。

我不知道在PropertyGrid中直接格式化属性的方法,但你可以做类似的事情

 class MyData { [Browsable(false)] public int _MyProp { get; set; } [Browsable(true)] public string MyProp { get { return _MyProp.ToString("#,##0"); } set { _MyProp = int.Parse(value.Replace(".", "")); } } } 

PropertyGrid中仅显示Browsable(true)属性。