using System.Windows;
public T GetParentOfType<T>(DependencyObject element) where T : DependencyObject
{
Type type = typeof(T);
if (element == null)
return null;
DependencyObject parent = VisualTreeHelper.GetParent(element);
if (parent == null && ((FrameworkElement)element).Parent is DependencyObject)
parent = ((FrameworkElement)element).Parent;
if (parent == null)
return null;
else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type))
return parent as T;
return GetParentOfType<T>(parent);
}
사용법
System.Windows.Point point = new System.Windows.Point(Mouse.GetPosition(datagGrid).X, Mouse.GetPosition(datagGrid).Y);
HitTestResult hitTestResult = VisualTreeHelper.HitTest(datagGrid, point);
if (hitTestResult != null)
{
//LazySingleton은 싱글턴이라 static으로 함수를 만들던가 해야함.
DataGridCell cell = LazySingleton<SchoolDataUtil>.Instance.GetParentOfType<DataGridCell>(hitTestResult.VisualHit);
DataGridRow row = LazySingleton<SchoolDataUtil>.Instance.GetParentOfType<DataGridRow>(hitTestResult.VisualHit);
}
public static T GetParentOfType<T>(DependencyObject element) where T : DependencyObject
{
Type type = typeof(T);
if (element == null)
return null;
DependencyObject parent = VisualTreeHelper.GetParent(element);
if (parent == null && ((FrameworkElement)element).Parent is DependencyObject)
parent = ((FrameworkElement)element).Parent;
if (parent == null)
return null;
else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type))
return parent as T;
return GetParentOfType<T>(parent);
}
public class LazySingleton<T> where T : new()
{
private static readonly Lazy<T> instance = new Lazy<T>(() => new T(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
public static T Instance { get { return instance.Value; } }
private LazySingleton() { }
}
'WPF' 카테고리의 다른 글
06. WPF DataGridViewHelper (0) | 2020.08.21 |
---|---|
04. WPF MVVM(3) RelayCommand (0) | 2020.08.21 |
03. WPF MVVM(2) INotifyPropertyChanged (0) | 2020.08.21 |
02. WPF MVVM(1) View-ViewModel 연결 (0) | 2020.08.21 |
01. WPF DataGrid Text Center (0) | 2020.05.30 |