Posts

Showing posts from November, 2008

Typed Data Binding using Expression<T>

Use of System.Linq.Expression seems to be gaining momentum as a general-purpose tool for .NET programming. The first use that came to mind for me was as a mechanism for typed data binding. It has always bothered me that databinding mechanisms rely on the fragile (and unverifiable at compile-time) practice of passing the member in by name: name_textbox.DataBindings.Add("Text", person, "Name"); With the use of a fairly simple extension method, this can be made type-safe: name_textbox.Bind( () => name_textbox.Text, person, () => person.Name ); Here's the helper method: public static void Bind<ControlType, TSet, TGet>( this ControlType control, Expression<Func<TSet>> propSetter, object getter, Expression<Func<TGet>> propGetter) where ControlType : Control { control.DataBindings.Add( _memberName(propSetter), getter, _memberName(propGetter)); } private static string _memberName<TDelegate>( Expre...