Reputation: 300
I'm binding a domain objects property to the Text property of a System.Windows.Forms.Label using the DataBindings
:
Label l = new Label();
l.DataBindings.Add(new Binding("Text",myDomainObject,"MyProperty"));
However, when I change the domain object, the Label does not reflect the change. I know that for complex Controls like the DataGridView, binding can be done with a BindingSource on which I can call ResetBindings, but I couldn't find any method to update the binding in the simple case of a Label.
Upvotes: 3
Views: 7213
Reputation: 178820
Your domain object should implement INotifyPropertyChanged so that the binding knows when the underlying property has changed.
Upvotes: 4
Reputation: 29274
Kent has the correct answer, but I want to add a little tidbit on applying INotifyPropertyChanged
interface.
To raise the event easily try this
protected void OnPropertyChanged<T>(Expression<Func<T>> property)
{
if (this.PropertyChanged != null)
{
var mex = property.Body as MemberExpression;
string name = mex.Member.Name;
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
and apply it like
{ // inside some method or property setter
OnPropertyChanged(() => this.MyProperty);
}
The only reason this is better than specifying the property by name, is that if you refactor, or just change the name of the property you won't have to manually change the implentation, but can let the compiler rename all the references automatically.
Upvotes: 8