[WPF] 자식요소 반환하기
자식명으로 자식객체를 반환하는 코드입니다.
using System.Windows; using System.Windows.Media;
namespace WpfApp { public class Helper { /// <summary> /// 자식요소를 가져옵니다. /// </summary> /// <typeparam name="T">타입입니다.</typeparam> /// <param name="parentObject">부모객체입니다.</param> /// <param name="childName">자식요소명입니다.</param> /// <returns>자식 요소(객체)가 반환됩니다.</returns> public static T FindChild<T>(DependencyObject parentObject, string childName) where T : DependencyObject { if (parentObject == null) return null;
T childT = null;
// 부모가 가진 자식요소 수를 가져옵니다. int childrenCount = VisualTreeHelper.GetChildrenCount(parentObject);
for (int i = 0; i < childrenCount; i++) { // 자식요소를 꺼냅니다. var child = VisualTreeHelper.GetChild(parentObject, i);
// 꺼내고자하는 타입인지 확인합니다. T childType = child as T;
if (childType == null) { // 타입이 안맞는 경우 재귀하여 자식의 자식을 검사합니다. childT = FindChild<T>(child, childName);
// 찾으면 멈춤 if (childT != null) break; } else if (!string.IsNullOrEmpty(childName)) { var frameworkElement = child as FrameworkElement;
// 자식요소의 이름이 같은지 확인합니다. if (frameworkElement != null && frameworkElement.Name == childName) { childT = (T)child; break; } } else { childT = (T)child; break; } }
return childT; } } }
|