I am looking into strong typed Windows Forms databinding using extension methods. I have got this far following help from Xavier as below:
using System;
usin
As the question has been edited to only include an answer, I'm including that answer here. The author probably should have left the original question alone and posted an answer to his own question. But it appears to be a very good solution.
Edit: I prefer this solution I found eventually in Google's cache (it has been deleted from the author's site) as it only needs one type specification. I don't know why the original author deleted it.
// Desired call syntax:
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.
// Implementation.
public static class ControlExtensions
{
public static Binding Bind
(this TControl control,
Expression> controlProperty,
object dataSource,
Expression> dataSourceProperty)
where TControl: Control
{
return control.DataBindings.Add
(PropertyName.For(controlProperty),
dataSource,
PropertyName.For(dataSourceProperty));
}
}
public static class PropertyName
{
public static string For(Expression> 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;
}
}