■ VisualTreeHelper 클래스의 GetChildrenCount/GetChild 정적 메소드를 사용해 DependencyObject 객체에서 특정 타입의 첫번째 자손 객체를 구하는 방법을 보여준다.
※ 자식과 손자 객체까지만 탐색한다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
using System.Linq; using System.Collections.Generic; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Media; #region 첫번째 자손 객체 구하기 - GetFirstDescendantObjectOfType<TDescendant>(sourceObject) /// <summary> /// 첫번째 자손 객체 구하기 /// </summary> /// <typeparam name="TDescendant">자손 타입</typeparam> /// <param name="sourceObject">소스 객체</param> /// <returns>자손 객체</returns> public TDescendant GetFirstDescendantObjectOfType<TDescendant>(DependencyObject sourceObject) where TDescendant : DependencyObject { IEnumerable<DependencyObject> childObjectEnumerable = sourceObject.GetDescendantObjectEnumerableOfType<TDescendant>(); return childObjectEnumerable.FirstOrDefault(); } #endregion #region 자손 객체 열거 가능형 구하기 - GetDescendantObjectEnumerableOfType<TDescendant>(sourceObject) /// <summary> /// 자손 객체 열거 가능형 구하기 /// </summary> /// <typeparam name="TDescendant">자손 타입</typeparam> /// <param name="sourceObject">소스 객체</param> /// <returns>자손 객체 열거 가능형</returns> private IEnumerable<TDescendant> GetDescendantObjectEnumerableOfType<TDescendant>(DependencyObject sourceObject) where TDescendant : DependencyObject { IEnumerable<DependencyObject> childObjectEnumerable = GetDescendantObjectEnumerable(sourceObject); return childObjectEnumerable.OfType<TDescendant>(); } #endregion #region 자손 객체 열거 가능형 구하기 - GetDescendantObjectEnumerable(sourceObject) /// <summary> /// 자손 객체 열거 가능형 구하기 /// </summary> /// <param name="sourceObject">소스 객체</param> /// <returns>자손 객체 열거 가능형</returns> private IEnumerable<DependencyObject> GetDescendantObjectEnumerable(DependencyObject sourceObject) { Queue<DependencyObject> queue = new Queue<DependencyObject>(); int count1 = VisualTreeHelper.GetChildrenCount(sourceObject); for(int i = 0; i < count1; i++) { DependencyObject childObject = VisualTreeHelper.GetChild(sourceObject, i); yield return childObject; queue.Enqueue(childObject); } while(queue.Count > 0) { DependencyObject parentObject = queue.Dequeue(); int count2 = VisualTreeHelper.GetChildrenCount(parentObject); for(int i = 0; i < count2; i++) { DependencyObject childDependencyObject = VisualTreeHelper.GetChild(parentObject, i); yield return childDependencyObject; queue.Enqueue(childDependencyObject); } } } #endregion |