When your application uses DataBinding in WPF, it’s great how little you actually have to do to have full two-way databinding running, with multiple views watching the same data, and reacting based on data changes. This amazingly powerful feature is, to me, one of the key selling features of WPF and Silverlight; no longer do you have to write huge amounts of code in your Windows Forms or ASP.NET application to manage all the different views on the same data. The underlying platform takes care of it for you.
One of the key components in this “magic”, is the use of INotifyPropertyChanged, which is responsible for notifying the data consumers that properties have changed. In your property setter, all you need to do is call the PropertyChanged event, telling it which property has changed and off you go – support for two-way databinding. This means that the following code is a common site
On the surface, there doesn’t appear to be much wrong with it, but there is a flaw with this approach. What happens if your value doesn’t change, but the setter is called – this can happen if the user retypes a value that is already in the field for instance, WPF will trigger the setter even though nothing has changed, which results in the PropertyChanged event being raised, triggering rebinds. In a desktop application, this normally isn’t that significant, but it could be much more significant in a Silverlight app with heavy data binding. We know what the problem is, the Change method being called when nothing has changed, and the fix is easy. Check to see if the old value of the property differs from the new value, and call the Changed method only when they do. This simple change means that databindings only occur when something has actually changed.
2 thoughts on “The notification gotcha.”
I’m new to coding in WPF and its really great to get a look at the code of someone who knows what they’re doing. I really like this test you’ve added I think it makes a lot of sense even on a lightly loaded binding.
Ed – I’m glad you like it. Little tricks like this really help you grow as a developer.