James Joshua Street
James Joshua Street

Reputation: 3409

When do I detach event handlers in a control?

so I have a control whose panel attaches these events inside the panel's initialized event:

  gvvm = DataContext as GraphViewerViewModel;
  gvvm.ZoomToFitEvent += new EventHandler(_GraphViewerViewModel_ZoomToFitEvent);
  gvvm.ZoomInEvent += new EventHandler(_GraphViewerViewModel_ZoomInEvent);
  gvvm.ZoomOutEvent += new EventHandler(_GraphViewerViewModel_ZoomOutEvent);
  gvvm.CloseVCDEvent += new EventHandler(gvvm_CloseVCDEvent);
  gvvm.LoadVCDEvent += new EventHandler(gvvm_LoadVCDEvent);
  gvvm.ScrollToTimeEvent += new EventHandler<GraphViewerViewModel.ScrollToTimeEventArgs>(gvvm_ScrollToTimeEvent);

Question 1. When should I detach the events? Is is appropriate to do so in panel.unloaded?

question 2. Is it appropriate to use events to communicate from your view model to your view? it seemed more reasonable than creating a property bool and doing actions in the panel based on the propertychanged event, though that has the advantage of not requiring me to subscribe/unsubscribe events. But the downside is I have to think of reasonable names for a property event toggle.

Upvotes: 0

Views: 436

Answers (1)

dev hedgehog
dev hedgehog

Reputation: 8791

Answer to question #1 is yeaaahhh, kinda, Unloaded event should serve for releasing resources.

However if the event handler is living only inside the control and you know that the control is not gonna be added or removed from VisualTree constantly during runtime then you could let the garbage collector do the job for you. Means once nobody holds the instance to your control the garbage collector will collect all of it anyways.

Answer to question #2: Read what Bernard said. The communication between View and ViewModel should not exist. However the ViewModel may communicate with the View which is the case everytime you set a Binding or you use INotifyPropertyChanged interface.

Upvotes: 1

Related Questions