I'm not aware of any library that does this - but you could write your own fairly easily.
Here's a basis I knocked up in a few minutes that establishes two way data binding between two simple properties:
public static class Binder
{
public static void Bind(
INotifyPropertyChanged source,
string sourcePropertyName,
INotifyPropertyChanged target,
string targetPropertyName)
{
var sourceProperty
= source.GetType().GetProperty(sourcePropertyName);
var targetProperty
= target.GetType().GetProperty(targetPropertyName);
source.PropertyChanged +=
(s, a) =>
{
var sourceValue = sourceProperty.GetValue(source, null);
var targetValue = targetProperty.GetValue(target, null);
if (!Object.Equals(sourceValue, targetValue))
{
targetProperty.SetValue(target, sourceValue, null);
}
};
target.PropertyChanged +=
(s, a) =>
{
var sourceValue = sourceProperty.GetValue(source, null);
var targetValue = targetProperty.GetValue(target, null);
if (!Object.Equals(sourceValue, targetValue))
{
sourceProperty.SetValue(source, targetValue, null);
}
};
}
}
Of course, this code lacks a few niceties. Things to add include
- Checking that
source
and target
are assigned
- Checking that the properties identified by
sourcePropertyName
and targetPropertyName
exist
- Checking for type compatibility between the two properties
Also, Reflection is relatively slow (though benchmark it before discarding it, it's not that slow), so you might want to use compiled expressions instead.
Lastly, given that specifying properties by string is error prone, you could use Linq expressions and extension methods instead. Then instead of writing
Binder.Bind( source, "Name", target, "Name")
you could write
source.Bind( Name => target.Name);