
ひさしぶりにWindowds formsのプログラムをC#で作成中にコントロールにデータバインドをしようとしたら、ListBoxなど一部のコントロールでは<INotifyPropertyChangedを使った更新が効かないことが分かったので、BindingListで使用したのでメモ。(というか本来ListboxにバインドできるのはSelectedIndex ,SelectedItem ,SelectedValue,Tagだけらしい)。
ここでBindingListを使わずにtestclassを直にDataSourceにバインドすると、PropertyChangedがnullとなる。
t = new testclass();
t.display = "one";
testdata = new BindingList<testclass>();
testdata.Add(t);
listBox1.DisplayMember = nameof(display);
listBox1.DataSource = testdata;
ついでによく忘れるので、INotifyPropertyChangedの書き方。
using System.ComponentModel;
public class testclass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public string _display;
public string display
{
get { return _value; }
set {
if (value != _display){
_display= value;
NotifyPropertyChanged(nameof(display));
}
}
}
}
ほかにもいろんなやりかたがあるらしい。参考はこのページ「
データ バインディング - .NET でデータ バインディングを適切に実装する方法」です。