为什么BindingSource没有告诉我哪个属性已经改变了? [英] Why does BindingSource not tell me which property has changed?
问题描述
然而 - 当CurrentItemChanged事件告诉我什么时候一个财产已经改变,它不告诉我哪一个 - 这是我需要的重要部分。
有没有办法找出哪个属性正在改变?
您的数据对象需要实现INotifyPropertyChanged界面:
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);
}
}
}
}
然后如果您使用BindingList,您可以使用BindingSource的ListChanged事件来查看哪个属性已更改:
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 =更改文本;
}
void bs_ListChanged(object sender,ListChangedEventArgs e){
if(e.PropertyDescriptor!= null){
MessageBox.Show(e.PropertyDescriptor.Name );
}
}
另请参阅实现INotifyPropertyChanged - 存在更好的方法?
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?
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?
这篇关于为什么BindingSource没有告诉我哪个属性已经改变了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!