Databinding proves to be very useful in some cases, but often turns out to be a maintenance nightmare. Since it requires strings with the property names to be passed as parameters of the Binding object. When the class, where a textbox is binded to, changes over time, so do property names. But since these property names are passed around as a string, they do not raise compile errors, causing unexpected behaviour of the application.
Here’s how you can make these bindings strongly typed, causing compilation errors if the property name of a class would change. Imagine we would like to bind a textbox to the Name property of the Person class, here’s the function that is going to help us. This function has a lambda expression returning a string and receiving a Person as parameter.
public string GetPropertyName(Expression<Func<Person, string>> propertySelector) { MemberExpression memberExpression = propertySelector.Body as MemberExpression; MemberInfo propertyInfo = memberExpression.Member; return propertyInfo.Name; }
The original binding code would like this, notice the “Name” string.
m_TextEditPerson.DataBindings.Add(new Binding("Text", m_Person, "Name"));
Here’s the new binding statement.
m_TextEditPerson.DataBindings.Add(new Binding("Text", m_Person, GetPropertyName(x => x.Name)));
