I was recently inspired by a question about property names in strings on Stack Overflow. The problem is that Windows Forms data binding takes the names of properties to bind as string parameters and if these properties change or are removed, errors won't surface until the bound control is exercised at run-time. So, using Paul's strongly typed property name ideas, I propose this alternative syntax for programmatic data binding in Windows Forms:
nameTextBox.Bind(t => t.Text, aBindingSource, (Customer c) => c.FirstName);
// Binds the Text property on nameTextBox to the FirstName property
// of the current Customer in aBindingSource, no string literals required.
And the following code to implement support for it:
public static class ControlExtensions
{
public static Binding Bind(this TControl control, Expressionobject>> controlProperty, object dataSource, Expressionobject>> dataSourceProperty) where TControl: Control
{
return control.DataBindings.Add(PropertyName.For(controlProperty), dataSource, PropertyName.For(dataSourceProperty));
}
}
public static class PropertyName
{
public static string For(Expressionobject>> property)
{
var member = property.Body as MemberExpression;
if (null == member)
{
var unary = property.Body as UnaryExpression;
if (null != unary) member = unary.Operand as MemberExpression;
}
return null != member ? member.Member.Name : string.Empty;
}
}
Thoughts? Overkill?