-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisualTreeExtensions.cs
More file actions
65 lines (53 loc) · 1.78 KB
/
Copy pathVisualTreeExtensions.cs
File metadata and controls
65 lines (53 loc) · 1.78 KB
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
using System;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;
namespace DiagramDesigner
{
public static class VisualTreeExtensions
{
public static T GetVisualAncestor<T>(this DependencyObject d) where T : class
{
DependencyObject item = VisualTreeHelper.GetParent(d);
while (item != null)
{
T itemAsT = item as T;
if (itemAsT != null) return itemAsT;
item = VisualTreeHelper.GetParent(item);
}
return null;
}
public static DependencyObject GetVisualAncestor(this DependencyObject d, Type type)
{
DependencyObject item = VisualTreeHelper.GetParent(d);
while (item != null)
{
if (item.GetType() == type) return item;
item = VisualTreeHelper.GetParent(item);
}
return null;
}
public static T GetVisualDescendent<T>(this DependencyObject d) where T : DependencyObject
{
return d.GetVisualDescendents<T>().FirstOrDefault();
}
public static IEnumerable<T> GetVisualDescendents<T>(this DependencyObject d) where T : DependencyObject
{
int childCount = VisualTreeHelper.GetChildrenCount(d);
for (int n = 0; n < childCount; n++)
{
DependencyObject child = VisualTreeHelper.GetChild(d, n);
if (child is T)
{
yield return (T)child;
}
foreach (T match in GetVisualDescendents<T>(child))
{
yield return match;
}
}
yield break;
}
}
}