简体   繁体   中英

wpf userControl's child controls' unsubscribe events

I am hoping to have a generic (extension) method which takes parent control and traverse through to its all children controls and unsubscribe their events if any.

problem i am closely looking at memory consumption when i create some wpf based form, memory spike which is expected considering the number of ui elements and their events but when form closes i expect to memory get release as in wpf, im assuming form get disposed automatically disposed once closed so GC should clean up and release the memory... but thats what not happening as i waited few minutes and looked on private memory usage in diagnostic tools, that remains same. so im wondering its not completely disposing/unsubscribing events etc

I can't speak to whether or not having many subscribed events negatively affects performance, but I can certainly answer your other two questions:

  1. You can use the following extension to enumerate all children:

     public static IEnumerable<T> GetVisualChildren<T>(this DependencyObject Parent) where T : DependencyObject { if (Parent != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(Parent); i++) { var Child = VisualTreeHelper.GetChild(Parent, i); if (Child != null && Child is T) yield return (T)Child; foreach (var ChildOfChild in GetVisualChildren<T>(Child)) yield return ChildOfChild; } } } foreach (myControlInstance.GetVisualChildren<DependencyObject>()) { //Unsubscribe events }
  2. To unsubscribe all events from the object, refer to this SO article:

How do I unsubscribe all handlers from an event for a particular class in C#?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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