简体   繁体   English

何时在控件中分离事件处理程序?

[英]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? 问题1.我应该何时分离事件? Is is appropriate to do so in panel.unloaded? 是否适合在panel.unloaded中这样做?

question 2. Is it appropriate to use events to communicate from your view model to your view? 问题2.使用事件从视图模型到视图进行通信是否合适? 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. 这似乎比创建property bool和基于propertychanged事件在面板中执行操作更合理,尽管这样做的好处是不需要我订阅/取消订阅事件。 But the downside is I have to think of reasonable names for a property event toggle. 但是缺点是我必须考虑属性事件切换的合理名称。

Answer to question #1 is yeaaahhh, kinda, Unloaded event should serve for releasing resources. 问题1的答案是yeaaahhh,有点,Unloaded事件应该用于释放资源。

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. 但是,如果事件处理程序仅驻留在控件内部,并且您知道在运行时期间不会不断从VisualTree中添加或删除控件,则可以让垃圾收集器为您完成这项工作。 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. 对问题2的回答:阅读伯纳德的讲话。 The communication between View and ViewModel should not exist. View和ViewModel之间的通信不应存在。 However the ViewModel may communicate with the View which is the case everytime you set a Binding or you use INotifyPropertyChanged interface. 但是,每次您设置Binding或使用INotifyPropertyChanged接口时,ViewModel都可能与View通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM