这个示例展示了如何创建一个自定义格式提供程序对象,它以二进制形式显示十进制值,但是仅当格式字符串被设置为“B”时才这样显示。 请参阅 自定义格式设置 主题,了解关于创建自定义格式提供程序的信息。
结果如下图所示。
C# | 复制代码 |
---|---|
// A custom formatter object. public class BaseFormatter : IFormatProvider, ICustomFormatter { // The GetFormat method of the IFormatProvider interface. // This must return an object that provides formatting services for the specified type. public object GetFormat(Type format) { if (format == typeof (ICustomFormatter)) return this; else return null; } // The Format method of the ICustomFormatter interface. // This must format the specified value according to the specified format settings. public string Format (string format, object arg, IFormatProvider provider) { if (format == null) { if (arg is IFormattable) return ((IFormattable)arg).ToString(format, provider); else return arg.ToString(); } if (format == "B") return Convert.ToString(Convert.ToInt32(arg), 2); else return arg.ToString(); } } // ... // Assign the custom formatter to the editor. spinEdit1.Properties.DisplayFormat.FormatType = FormatType.Custom; spinEdit1.Properties.DisplayFormat.FormatString = "B"; spinEdit1.Properties.DisplayFormat.Format = new BaseFormatter(); spinEdit1.Properties.IsFloatValue = false; spinEdit1.EditValue = 10; |
Visual Basic | 复制代码 |
---|---|
' A custom formatter object. Public Class BaseFormatter : Implements IFormatProvider, ICustomFormatter ' The GetFormat method of the IFormatProvider interface. ' This must return an object that provides formatting services for the specified type. Public Function GetFormat(ByVal format As Type) As Object _ Implements IFormatProvider.GetFormat If format.ToString() = GetType(ICustomFormatter).ToString() Then GetFormat = Me Else GetFormat = Nothing End If End Function ' The Format method of the ICustomFormatter interface. ' This must format the specified value according to the specified format settings. Public Function Format(ByVal formatString As String, ByVal arg As Object, _ ByVal provider As IFormatProvider) As String Implements ICustomFormatter.Format If (formatString = Nothing) Then If TypeOf arg Is IFormattable Then Format = CType(arg, IFormattable).ToString(formatString, provider) Else Format = arg.ToString() End If Exit Function End If If (formatString = "B") Then Format = Convert.ToString(Convert.ToInt32(arg), 2) Else Format = arg.ToString() End If End Function End Class ' ... ' Assign the custom formatter to the editor. SpinEdit1.Properties.DisplayFormat.FormatType = FormatType.Custom SpinEdit1.Properties.DisplayFormat.FormatString = "B" SpinEdit1.Properties.DisplayFormat.Format = New BaseFormatter() SpinEdit1.Properties.IsFloatValue = False SpinEdit1.EditValue = 10 |