using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;
using System.Linq;
namespace PageDemo
{
public static class Extensions
{
///
/// 获取该元素的可见树里面所有的子元素
///
/// 可见元素
public static IEnumerable GetVisualDescendants(this DependencyObject element)
{
return GetVisualDescendantsAndSelfIterator(element).Skip(1);
}
///
/// 获取该元素的可见树里面所有的子元素以及该元素本身
///
/// 可见元素
public static IEnumerable GetVisualDescendantsAndSelfIterator(DependencyObject element)
{
Queue remaining = new Queue();
remaining.Enqueue(element);
while (remaining.Count > 0)
{
DependencyObject obj = remaining.Dequeue();
yield return obj;
foreach (DependencyObject child in obj.GetVisualChildren())
{
remaining.Enqueue(child);
}
}
}
///
/// 获取该元素的可见树里面下一级的子元素
///
/// 可见元素
public static IEnumerable GetVisualChildren(this DependencyObject element)
{
return GetVisualChildrenAndSelfIterator(element).Skip(1);
}
///
/// 获取该元素的可见树里面下一级的子元素以及该元素本身
///
/// 可见元素
public static IEnumerable GetVisualChildrenAndSelfIterator(this DependencyObject element)
{
yield return element;
int count = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < count; i++)
{
yield return VisualTreeHelper.GetChild(element, i);
}
}
}
}
测试获取程序页面类
Test.cs
using System.Windows;
using Microsoft.Phone.Controls;
using System.Linq;
using System.Collections.Generic;
namespace PageDemo
{
public class Test
{
///
/// 获取当前的程序展示的页面
///
public static PhoneApplicationPage Page
{
get { return (Application.Current.RootVisual as PhoneApplicationFrame).GetVisualDescendants().OfType().FirstOrDefault(); }
}
///
/// 获取所有的框架下的页面
///
public static List Pages
{
get { return (Application.Current.RootVisual as PhoneApplicationFrame).GetVisualDescendants().OfType().ToList(); }
}
///
/// 获取程序所有的UI元素
///
public static List Elements
{
get { return (Application.Current.RootVisual as PhoneApplicationFrame).GetVisualDescendants().ToList(); }
}
}
}