I have a wpf app, MVVM-style, with a (Telerik Rad)Gridview. I want to have an event every time user updates a cell.
The GridView is bound to the MyRowModel
public class MyRowModel : INotifyPropertyChanged
{
//...
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
I want to handle them in my View Model, I bind them like this
var rows = MyRows.ForEach(p=> p.PropertyChanged += MyPropertyChangedHandler);
This works, but do I need to unbind the events somewhere? The user can move back from this view, and select another set of rows. Moreover I will get updated rows from servier every time there is a cell change.
2, bonus question) Are these (in my case MyRowModel ) View Models or Models?
but do I need to unbind the events somewhere?
It depends on the lifetime of the involved objects. If you don't want the MyRowModel
objects to prevent the view model from being garbage collection when you have navigated away from it, you should unregister the event handlers when the view is Unloaded
and register them when it is Loaded
:
MyRows.ForEach(p=> p.PropertyChanged -= MyPropertyChangedHandler);
If items are dynamically added to and removed from MyRows
, you should also detect when this happens and register and unregister the event handler accordingly. If MyRows
is an ObservableCollection<T>
, you could handle the CollectionChanged
event.
If you consider using weak events, you should also consider the semantic differences between using the WeakEventManager
and the +=
operator to hook up event handlers.