I have an object that I have bound to a control on a form using C# WinForms (targetting .NET 4.5.2). I have implemented INotifyPropertyChanged
, and when I modif
Ivan showed you how to solve the problem. Here in this answer I'll try to show you what the problem is and why it works this way.
Short answer
Your label is bound to an object not the variable. The variable is just like a pointer to the object. So replacing the variable doesn't have any impact on the object which your label is using as data source. Just the variable points to the new object. But your label is using the previous object. It has its own pointer to the previous object.
Consider these facts to know what is happening:
User currentUser = new User("Example Name");
When you assign an object to a variable, in fact the variable points to the object.
lblName.DataBindings.Add("Text", currentUser, "Name");
currentUser.Name = "Blahblah";
You changed the value of Name
property and since you implemented INotifyPropertyChanged
the control will be notified of changes and will refresh its Text
.
But the main statement which didn't work as you expected:
currentUser = new User("New Name");
Here you made the currentUser
variable point to another object. It doesn't have anything to do with the previous object which it was pointing to. It just points to another object.
The Binding
which you added to the label, still uses the previous object.
So it's normal to not have any notification, because the object which is in use by the label didn't changed.
How the BindingSource solved the problem?
The BindingSource
raises ListChanged
event when you assign a new object to its DataSource
and it makes the BindingObject
fetch new value from DataSource
and refresh Text
property. You can take a look at this post: How to make a binding source aware of changes in its data source?