Reputation: 5490
I'm looking at using databinding - and the simplest thing to do seems to be to use a BindingSource to wrap my data objects.
However - while the CurrentItemChanged event tells me when a property has changed, it doesn't tell me which one - and that's a vital part of what I need.
Is there any way to find out which property is changing?
Upvotes: 4
Views: 2520
Reputation: 81610
Your data objects need to implement the INotifyPropertyChanged interface:
public class MyObject : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private string textData = string.Empty;
protected void OnPropertyChanged(string propertyName) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string TextData {
get { return textData; }
set {
if (value != textData) {
textData = value;
OnPropertyChanged("TextData");
}
}
}
}
Then if you use BindingList, you can use the BindingSource's ListChanged event to see which property changed:
BindingList<MyObject> items = new BindingList<MyObject>();
BindingSource bs = new BindingSource();
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
items.Add(new MyObject() { TextData = "default text" });
bs.DataSource = items;
bs.ListChanged += bs_ListChanged;
items[0].TextData = "Changed Text";
}
void bs_ListChanged(object sender, ListChangedEventArgs e) {
if (e.PropertyDescriptor != null) {
MessageBox.Show(e.PropertyDescriptor.Name);
}
}
Also see Implementing INotifyPropertyChanged - does a better way exist?
Upvotes: 4