ListDataBindingsAttribute

先日の日記ではListBox、ComboBox等のリスト形式のデータを持つコントロールのデータバインディングをカスタム属性によって制御する方法について書いた。

リスト項目をバインドするための新たなカスタム属性を用意する必要があるだろう。それに関しては次回のエントリで。

これに関してはなんてことは無い、ListDataBindingsAttributeというカスタム属性クラスをDataBindingsAttributeから派生して、DisplayMember"と"ValueMember"プロパティを実装し、DataSourceプロパティを書き換えた後にこれらのプロパティをコントロールのプロパティに転記してやるだけだ。

string valueMember = (attr as ListDataBindingsAttribute).ValueMember;
if (!String.IsNullOrEmpty(valueMember)) {
    PropertyInfo valueMemberPropInfo = control.GetType().GetProperty("ValueMember");
    valueMemberPropInfo.SetValue(control, valueMember, null);
}
string displayMember = (attr as ListDataBindingsAttribute).DisplayMember;
if (!String.IsNullOrEmpty(displayMember))
{
    PropertyInfo displayMemberPropInfo = control.GetType().GetProperty("DisplayMember");
    displayMemberPropInfo.SetValue(control, displayMember, null);
}

ここまではTextBoxやLabel等の単項目データと、ListBoxやComboBoc等のリスト項目データを扱うコントロールのデータバインディングをカスタム属性により制御してきたが、このまま進めていくと、データバインディングの種類ごとに対応していくことになってしまいそうだ。どうせ.NET Framework2.0を使用しているのであればやはりBindingSourceクラスを使わない手は無いと思うので、今後はBindingSourceを上手く使う方向で考えていく予定。