The databinding functionality for Windows Forms is pretty easy to use if not a little basic. However, the bindings do allow you to assign an IFormatProvider which would mean to me that you could format the data in any way you want. However, it appears that the formatting only applies for the purpose of globalization.
Instead, if you want custom formatting (ICustomFormatter) for your data you'll need to handle the Format event of the binding. You'll also have to handle the Parse event if your parseable data is not directly convertible to the underlying type and you want update functionality. Simply put the Format event allows you to tweak the value before it's displayed and the Parse event allows you to untweak the displayed value back to a value that the underlying type understands.
My example illustrates a simple binding using a formatter that pulls value from a resource file based on the default string representation of the object. In my case the object is a TraceLevel enumeration where I want to display "Error", "Warning", "Information", and "Debug" instead of "Error", "Warning", "Info", and "Verbose". I could have created a separate enumeration, but I still would have had the localization issue.
The data binding code is pretty simple:
Binding levelBinding = levelEditor.DataBindings.Add("Value", LogEntry,
"MessageLevel", true, DataSourceUpdateMode.Never, null, null,
MessageLevelFormatter.Instance);
levelBinding.Format += (sender, e) =>
e.Value = MessageLevelFormatter.Instance.Format(null, e.Value,
CultureInfo.CurrentCulture);
The ICustomFormatter and IFormatProvider code is also simple:
public class MessageLevelFormatter : IFormatProvider, ICustomFormatter
{
private static MessageLevelFormatter instance = new MessageLevelFormatter();
public static MessageLevelFormatter Instance
{
get
{
return instance;
}
}
public object GetFormat(Type formatType)
{
return (formatType == typeof(ICustomFormatter) ? this : null);
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg == null)
return null;
return Resources.ResourceManager.GetString(arg.ToString())
?? arg.ToString();
}
}