Should I always implement INotifyPropertyChanged interface in model?

544 views Asked by At

If I have a model which is pretty much a readonly collection and dispayed on a grid, where the user selects a row.

Do I need to have INotifyPropertyChanged always implemented on the model? Is there a performance benefit of implementing vs not?

I would like to know if performance is impacted by UI trying to use something like

var x = Model as INotifyPropertyChanged;

which it wouldn't have used otherwise.

2

There are 2 answers

2
Mike Strobel On BEST ANSWER

If you are using the model in any data bindings, then yes, you should implement INotifyPropertyChanged even if it is completely immutable. The reason has nothing to do with performance, but to avoid a memory leak.

A Binding will always try to register for change notifications, and if you do not implement INotifyPropertyChanged or expose discrete change events of the form [Property]Changed, it will register through the PropertyDescriptor API. The default, reflection-based PropertyDescriptor implementation uses a global subscription table, and if for some reason the Binding does not unsubscribe cleanly, your view model will be kept alive indefinitely. This is in contrast to the weak event pattern used when bindings subscribe to INotifyPropertyChanged notifications. Bindings at runtime generally clean up after themselves, but the Xaml designer is notorious for leaking under these circumstances, causing your designer process's memory consumption to rise steadily as you work.

0
123 456 789 0 On

If you are just displaying in on a DataGrid and not expecting any UI interaction that'll change the value of the Model then you do not have to implement INPC.

WPF is tied to the INPC mechanism to update the UI from the backing Model. You don't need it if you load it once and won't change again. However, INPC can be pretty handy and you need to implement it if say a business logic that requires you to update something to a different row then you can basically subscribe the other model's PropertyChangedEvent to do something to the other row when a property changed is raised.

There is no performance benefit of implementing it.