通过自定义类实现接口ICustomFormatter和IFormatProvider来实现输出格式化
使用格式自定义类让表格数据自动根据配置的计量单位来处理数据的计量单位转化和显示:
Public Function Format(format1 As String, arg As Object, formatProvider As System.IFormatProvider) As String Implements System.ICustomFormatter.Format
If (String.IsNullOrEmpty(format1)) Then
If (arg Is GetType(IFormattable)) Then
Return CType(arg, IFormattable).ToString(format1, formatProvider)
ElseIf (arg Is Nothing) Then
Return String.Empty
Else
Return arg.ToString()
End If
Else
If (arg Is Nothing) Then
Return String.Empty
ElseIf (IsNumeric(arg)) Then
If ([Enum].IsDefined(GetType(EMUnitClass), format1)) Then
Dim pUnitClass As EMUnitClass
pUnitClass = CType([Enum].Parse(GetType(EMUnitClass), format1), EMUnitClass)
Return Me.formatByUnitClass(pUnitClass, Convert.ToDouble(arg))
Else
If (arg Is GetType(IFormattable)) Then
Return CType(arg, IFormattable).ToString(format1, formatProvider)
Else
Return arg.ToString()
End If
End If
Else
Return arg.ToString()
End If
End If
End Function
Public Function GetFormat(formatType As System.Type) As Object Implements System.IFormatProvider.GetFormat
If (formatType Is GetType(ICustomFormatter)) Then 'OrElse formatType Is GetType(NumberFormatInfo)
Return Me
Else
Return Nothing
End If
End Function
显示指定DataGridViewRow的Column的FormatPrivider
pColumn.DefaultCellStyle.FormatProvider = MyHub.mModuleMain.mUnitManager ‘自定义的类
如果以为这样子就可以实现自定义格式化,那就大错特错了,还需要指定CellFormatting事件才能真正启用自定义格式化功能
Private Sub xDataGridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles xDataGridView1.CellFormatting
If (TypeOf e.CellStyle.FormatProvider Is ICustomFormatter AndAlso (Not String.IsNullOrEmpty(e.CellStyle.Format))) Then
e.Value = CType(e.CellStyle.FormatProvider.GetFormat(GetType(ICustomFormatter)), ICustomFormatter).Format(e.CellStyle.Format, e.Value, e.CellStyle.FormatProvider)
e.FormattingApplied = True
End If
End Sub
参考的C#实现例子
public class MyEnumFormatter : IFormatProvider, ICustomFormatter {
public object GetFormat(Type formatType) {
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider) {
return ((NameOfEnumType)Convert.ToInt32(arg)).ToString();
}
}
void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
if (e.CellStyle.FormatProvider is ICustomFormatter) {
e.Value = (e.CellStyle.FormatProvider.GetFormat(typeof(ICustomFormatter)) as ICustomFormatter).Format(e.CellStyle.Format, e.Value, e.CellStyle.FormatProvider);
e.FormattingApplied = true;
}
}