是否可以格式化PropertyGrid中显示的winforms数值属性?属性网格编号格式
class MyData
{
public int MyProp {get; set;}
}
而我希望它在网格中显示为1.000.000例如。
这是否有一些属性?
是否可以格式化PropertyGrid中显示的winforms数值属性?属性网格编号格式
class MyData
{
public int MyProp {get; set;}
}
而我希望它在网格中显示为1.000.000例如。
这是否有一些属性?
你应该实现自定义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 w orks以及如何定制。
作为一个有趣的调整,参数'context.Instance'指向所显示的对象,如果存在任何格式化线索(如格式字符串属性),则可以在'ToString()'中使用它们。 – ja72 2016-03-24 20:55:31
我不知道怎样的性能直接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(".", ""));
}
}
}
只有Browsable(true)
属性显示在PropertyGrid中。
这实际上是我首选的解决方案,因为可用的自定义级别。 – ja72 2013-10-08 21:30:42
也更简洁。 – 2015-04-20 09:58:01
真棒的想法))) – 2015-11-24 18:02:06
这看起来应该是三个属性,即主要,次要,修订。如果可能的话,你将需要编写自己的格式程序,你可以使用String.Format – Kcvin 2013-05-14 11:14:21
OP使用欧洲编号方案,千位分隔符是'.'而不是'',就像美国一样。所以这个问题并不涉及'版本'格式,而是数字格式。 – ja72 2013-10-02 15:07:30