using System; using System.Collections.Generic; using System.Windows; namespace C4IT_CustomerPanel.libs { class visualHelper { public static List GetLogicalChildCollection(object parent) where T : DependencyObject { List logicalCollection = new List(); GetLogicalChildCollection(parent as DependencyObject, logicalCollection); return logicalCollection; } private static void GetLogicalChildCollection(DependencyObject parent, List logicalCollection) where T : DependencyObject { System.Collections.IEnumerable children = LogicalTreeHelper.GetChildren(parent); foreach (object child in children) { if (child is DependencyObject) { DependencyObject depChild = child as DependencyObject; if (child is T) { logicalCollection.Add(child as T); } GetLogicalChildCollection(depChild, logicalCollection); } } } public static T FindVisualChild(DependencyObject parent, string Tag = null) where T : DependencyObject { try { var Cnt = System.Windows.Media.VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < Cnt ; i++) { DependencyObject child = System.Windows.Media.VisualTreeHelper.GetChild(parent, i); string _Tag = (child as FrameworkElement)?.Tag as string; if (child is T visualChild && (Tag == null || _Tag == Tag)) { return visualChild; } else { T childOfChild = FindVisualChild(child, Tag); if (childOfChild != null) return childOfChild; } } } catch (Exception) { } return null; } public static Window GetMainWindow() { return Application.Current.MainWindow; } public static Window GetUserControlOwnerWindow(System.Windows.Forms.Control usercontrol) { return GetUserControlOwnerWindow(usercontrol.Parent); } // ****************************************************************** public static Window GetUserControlOwnerWindow(DependencyObject parent) { while (parent != null && !(parent is Window)) { parent = LogicalTreeHelper.GetParent(parent); } return parent as Window; } } }