How to: Create a Custom Formatter to Change the Case of String Values

  • 2 minutes to read

This sample creates a custom formatter that modifies the case of an editor's text. The editor's display text will obey the specified format string (the FormatInfo.FormatString property value). This string is passed to the Format method as the format parameter. If this parameter value is 'u', the display value is converted to upper case, if the format string is 'l', it is converted to lower case.

The following image shows the text editors' appearance before and after sample code execution.

CustomFormatting_example

// 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();

See also: RepositoryItemTextEdit.CharacterCasing.