There’s a lot of “goodness” buried in WinForms databinding that doesn’t get to see the light of day. Here’s one example I discovered just today …
When you set up a Binding, one of the possible parameters is a boolean value for enable formatting:
var binding
= new Binding(
"EditValue", // Name of the control property to bind
aSubject, // Data source
aProperty, // Path of property on the data source
true, // Is Formatting Enabled
DataSourceUpdateMode.OnPropertyChanged);
The interesting thing is that turning enable formatting on does more than enable the Format
and Parse
events.
Check out the OnFormat()
method of the Binding
object, for example:
protected virtual void OnFormat(ConvertEventArgs cevent)
{
if (onFormat != null)
{
onFormat(this, cevent);
}
if (!formattingEnabled
&& !(cevent.Value is DBNull)
&& cevent.DesiredType != null
&& !cevent.DesiredType.IsInstanceOfType(cevent.Value)
&& cevent.Value is IConvertible)
{
cevent.Value
= Convert.ChangeType(
cevent.Value,
cevent.DesiredType,
CultureInfo.CurrentCulture);
}
}
If you turn on formatting, you also turn on automatic conversions between types that implement IConvertible. Amongst other things, this allows you to databind to nullable properties.
Neat.