假设我有一个绑定到 BindingSource 的 DataGridView。BindingSource 有一个 MyClass 类的 DataSource
public class MyClass
{
public double Percentage {get; set;}
...
}
DataGridView 将百分比显示为双精度数。所以 19% 的值显示为 0.19,这不是我想要的。
幸运的是,我可以更改列的单元格样式:
dataGridViewCellStyle.Format = "p";
这使得该值根据当前区域性显示为百分比。在我的文化中,0.19 显示为 19%。
到目前为止,一切都很好。但是,如果操作员将此值更改为 18% 并结束编辑单元格,会发生什么情况。
- 引发事件 CellValidating。在这种情况下,我可以检查输入的文本是否为完美百分比。
然而,紧接着我得到一个异常,字符串“18%”不能被格式化为双精度。
我想我必须告诉 datagridviewCellStyle 使用哪个 formatprivider:
datagridVieCellStyle.FormatProvider = new MyFormatProvider();
class MyFormatProvider : IFormatProvider
{
public object GetFormat(Type formatType)
{
// what to return?
}
}
问题假设我有以下课程:
public static class PercentStringParser
{
public static double Parse(string txt);
}
我的格式提供者应该如何调用这个函数?