是否有任何数据绑定框架(BCL或其他)允许在实现INotifyPropertyChanged
和INotifyCollectionChanged
的任何两个CLR属性之间进行绑定?看起来应该可以做这样的事情:
var binding = new Binding();
binding.Source = someSourceObject;
binding.SourcePath = "Customer.Name";
binding.Target = someTargetObject;
binding.TargetPath = "Client.Name";
BindingManager.Bind(binding);
其中someSourceObject
和someTargetObject
只是实现INotifyPropertyChanged
的POCOs。然而,我不知道有任何BCL支持这一点,也不确定是否有现有的框架允许这样做。
更新:鉴于目前没有可用的库,我自己编写了自己的库。它可以在here上找到。
谢谢
发布于 2009-06-11 12:16:02
我写了Truss来填补这个空白。
发布于 2009-03-10 06:36:00
我不知道有什么库可以做到这一点--但是你可以很容易地编写你自己的库。
下面是我在几分钟内总结出的在两个简单属性之间建立双向数据绑定的基础:
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);
}
};
}
}
当然,这段代码缺少一些细节。要添加的内容包括
source
和target
是否为sourcePropertyName
和targetPropertyName
exist此外,反射相对较慢(尽管在丢弃它之前对其进行基准测试,它也不是那么慢),因此您可能希望使用编译后的表达式。
最后,考虑到通过字符串指定属性容易出错,您可以改用Linq表达式和扩展方法。那就不写了
Binder.Bind( source, "Name", target, "Name")
你可以写
source.Bind( Name => target.Name);
发布于 2009-03-06 00:42:00
AutoMapper可以在两个实例之间复制值,但您必须编写自己的代码才能自动执行此操作。
https://stackoverflow.com/questions/601880
复制相似问题