POCOプロパティ間でデータバインディングを行う簡単な方法を説明するこの投稿を見ていました:データバインディングPOCOプロパティ
Bevanによるコメントの1つには、このようなデータバインディングを実現するために使用できる単純なBinderクラスが含まれていました。それは私が必要とするものにはうまく機能しますが、クラスを改善するためにBevanが行った提案のいくつかを実装したいと思います。
- ソースとターゲットが割り当てられていることを確認する
- sourcePropertyNameおよびtargetPropertyNameで識別されるプロパティが存在することを確認します
- 2つのプロパティ間のタイプの互換性をチェックしています
また、文字列でプロパティを指定するとエラーが発生しやすいため、代わりにLinq式と拡張メソッドを使用できます。その後、書く代わりに
Binder.Bind( source, "Name", target, "Name")
あなたは書くことができます
source.Bind( Name => target.Name);
最初の3つは処理できると確信していますが(これらの変更を自由に含めることができます)、Linq式と拡張メソッドを使用して、プロパティ名の文字列を使用せずにコードを記述できるようにする方法がわかりません。
任意のヒント?
リンクにある元のコードは次のとおりです。
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);
}
};
}
}