これを行うライブラリは知りませんが、独自のライブラリをかなり簡単に作成できます。
以下は、2 つの単純なプロパティ間で双方向のデータ バインディングを確立するために、私が数分で作成した基礎です。
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
が存在することを確認する
- 2 つのプロパティ間の型の互換性を確認する
また、リフレクションは比較的遅いため (ただし、破棄する前にベンチマークを行いますが、それほど遅くはありません)、代わりにコンパイル済みの式を使用することをお勧めします。
最後に、プロパティを文字列で指定するとエラーが発生しやすいため、代わりに Linq 式と拡張メソッドを使用できます。次に、書く代わりに
Binder.Bind( source, "Name", target, "Name")
あなたが書くことができます
source.Bind( Name => target.Name);