Does Winforms DataBinding work for programmatically changed properties?
I have some UI controls that are usi开发者_JAVA百科ng DataBindings.Add method, and it works if I change the specified UI property by hand, or the source object is changed outside.
But if I invoke the UI.Property = value in code, then it doesn't change the UI nor the source object that's specified for DataBindings.Add.
What am I doing wrong? Am I using it incorrectly?
The control won't know that anything has changed unless the object implements INotifyPropertyChanged
. Then, the property setter in the object is changed to raise the PropertyChanged
event, passing in the name of the property that changed in the event arguments.
INotifyPropertyChanged
is a particular interface that the databinding mechanism in WinForms looks for when wiring up data binding. If it sees an object that implements that interface, it'll subscribe to its event, and you'll see your UI refreshed automatically without having to tell the databindings to re-read their values (which is what happens if you re-assign the DataSource
, etc).
Not obvious, but it makes sense when you think about. Without an event being broadcast, how would the UI control know that the property has changed? It's not polling the property every so often. It has to get told that the property changed, and the PropertyChanged
event is the conventional way to do that.
Something like (uncompiled code)...
public class MyInterestingObject : INotifyPropertyChanged
{
private int myInterestingInt;
public event PropertyChangedEventHandler PropertyChanged;
public int MyInterestingInt
{
get { return this.myInterestingInt; }
set
{
if (value != this.myInterestingInt)
{
this.myInterestingInt = value;
this.RaisePropertyChanged("MyInterestingInt");
}
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Now any code that has a databinding to that object's MyInterestingInt
property will update itself when that property is changed. (Some people get fancy with proxies to implement this interface for them.)
A caveat: be sure that you set the updated value before you raise the PropertyChanged
event! It's easy to do and can leave you scratching your head as to why the value isn't being updated.
精彩评论