forked from MaterialDesignInXAML/MaterialDesignInXamlToolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VisualTreeHelper.cs
56 lines (49 loc) · 1.83 KB
/
VisualTreeHelper.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using WPFVisualTreeHelper = System.Windows.Media.VisualTreeHelper;
namespace MaterialDesignThemes.Wpf.Tests
{
public static class VisualTreeHelper
{
public static T FindVisualChild<T>(this DependencyObject source, string name) where T : FrameworkElement
{
return GetAllVisualChildren(source).OfType<T>().Single(x => x.Name == name);
}
public static IEnumerable<T> GetVisualChildren<T>(this DependencyObject source) where T : DependencyObject
{
if (source == null) throw new ArgumentNullException(nameof(source));
return GetVisualChildrenImplementation();
IEnumerable<T> GetVisualChildrenImplementation()
{
int count = WPFVisualTreeHelper.GetChildrenCount(source);
for (int i = 0; i < count; i++)
{
if (WPFVisualTreeHelper.GetChild(source, i) is T child)
{
yield return child;
}
}
}
}
private static IEnumerable<DependencyObject> GetAllVisualChildren(DependencyObject source)
{
var stack = new Queue<DependencyObject>();
stack.Enqueue(source);
while (stack.Any())
{
DependencyObject current = stack.Dequeue();
int childCount = WPFVisualTreeHelper.GetChildrenCount(current);
for (int i = 0; i < childCount; i++)
{
var child = WPFVisualTreeHelper.GetChild(current, i);
yield return child;
stack.Enqueue(child);
}
}
}
}
}