这个示例创建了一个修改编辑器文本大小写的自定义格式提供程序。 编辑器将遵照指定的格式字符串来显示文本 (FormatInfo.FormatString 属性值)。 这个字符串被作为格式参数传递到 Format 方法。 如果这个参数值是 'u',那么显示值被转换为大写; 如果这个格式字符串是 'l',那么显示值被转换为小写。

请参阅 自定义格式设置 主题,了解关于创建自定义格式提供程序的信息。

下面的插图展示了文本编辑器的、在执行示例代码之前和之后的外观。

C#CopyCode image复制代码
// A custom formatter object.
class CustomFormatter : 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(System.Type type){
        return this;
    }
    // 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 formatProvider){
        string formatValue = arg.ToString();
        if (format == "u")
            return formatValue.ToUpper();
        else if (format == "l")
            return formatValue.ToLower();
        else return formatValue;
    }
}
// ...
// Assign the custom formatter to the editors.
textEdit1.Properties.DisplayFormat.FormatType = FormatType.Custom;
textEdit1.Properties.DisplayFormat.FormatString = "u";
textEdit1.Properties.DisplayFormat.Format = new CustomFormatter();

textEdit2.Properties.DisplayFormat.FormatType = FormatType.Custom;
textEdit2.Properties.DisplayFormat.FormatString = "l";
textEdit2.Properties.DisplayFormat.Format = new CustomFormatter();
Visual BasicCopyCode image复制代码
' A custom formatter object.
Class CustomFormatter : 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 type As Type) As Object _
    Implements IFormatProvider.GetFormat
        Return Me
    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 formatProvider As IFormatProvider) As String Implements ICustomFormatter.Format
        Dim formatValue As String = arg.ToString()
        If (formatString = "u") Then
            Format = formatValue.ToUpper()
        ElseIf formatString = "l" Then
            Format = formatValue.ToLower()
        Else
            Format = formatValue
        End If
    End Function
End Class
' ...
' Assign the custom formatter to the editors.
TextEdit1.Properties.DisplayFormat.FormatType = FormatType.Custom
TextEdit1.Properties.DisplayFormat.FormatString = "u"
TextEdit1.Properties.DisplayFormat.Format = New CustomFormatter()

TextEdit2.Properties.DisplayFormat.FormatType = FormatType.Custom
TextEdit2.Properties.DisplayFormat.FormatString = "l"
TextEdit2.Properties.DisplayFormat.Format = New CustomFormatter()