using System.Collections.Generic; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; namespace StrixMusic.Sdk.WinUI { /// /// A class of Visual Tree helper functions. /// public static class VisualTreeHelpers { /// /// Finds a child item through any levels in the VisualTree. /// /// The type of item being searched for. /// The parents item to be searched. /// All children of child to . /// /// https://stackoverflow.com/questions/34396002/how-to-get-element-in-code-behind-from-datatemplate /// public static IEnumerable FindVisualChildren(DependencyObject depObj) where T : DependencyObject { if (depObj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject child = VisualTreeHelper.GetChild(depObj, i); if (child != null && child is T) { yield return (T)child; } foreach (T childOfChild in FindVisualChildren(child!)) { yield return childOfChild; } } } } /// /// Finds a child item through any levels in the VisualTree with name a certain name. /// /// The type of the item being searched for. /// The parent item to be searched /// The name of the object being searched for. /// The first child found of type with the name . /// /// https://stackoverflow.com/questions/34396002/how-to-get-element-in-code-behind-from-datatemplate /// public static T GetDataTemplateChild(DependencyObject depObj, string? childName = null) where T : FrameworkElement { foreach (var item in FindVisualChildren(depObj)) { if (childName == null || item.Name == childName) { return item; } } return null!; } } }