0

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?

Cowborg
  • 2,645
  • 3
  • 34
  • 51
  • 1
    Try `WeakEvent`. You can use WPF implementation or open source. Finally, you can implement yourself. It is not a magic. –  Jul 06 '20 at 08:26
  • 1
    Question 1. Detach those event when you remove/delete any row from `GridView`. Question 2. Those ViewModel are `Models` as they don't have any `View` associated with them. – trix Jul 06 '20 at 08:30
  • Thanks both for your answers. I'll check out where I can detach the events and check out Weak Events also. Ok, that makes sense to call them models, since they dont have a view – Cowborg Jul 06 '20 at 08:48
  • @Cowborg What type is `MyRows`? How do you bind `MyRows`, can you show the XAML? How is this done _The user can move back from this view, and select another set of rows._? – thatguy Jul 06 '20 at 10:33

1 Answers1

1

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.

mm8
  • 163,881
  • 10
  • 57
  • 88