WPF中的VisualTreeHelper

VisualTreeHelper提供了一组WPF控件树模型,通过VisualTreeHelper可以遍历控件的树形结构,获取我们所需要的控件以及相应的属性;

VisualTreeHelper提供了一下4个方法:

1、FindElementsInHostCoordinates 检索一组对象,这些对象位于某一对象的坐标空间的指定点或 Rect 内。
2、GetChild 使用提供的索引,通过检查可视化树获取所提供对象的特定子对象。
3、GetChildrenCount 返回在可视化树中在某一对象的子集合中存在的子级的数目。
4、GetParent 返回可视化树中某一对象的父对象。

通俗点说:FindElementsInHostCoordinates常用于对象的碰撞检测,GetChild用于获取下级子对象(注意仅仅是下级,而非所有子对象,如果要获取所有子对象,需要自己写代码遍历),GetChildrenCount用于获取下级子对象的个数,GetParent用于获取某对象的上级子对象;

下面是简单的检索子对象的常用方法:

 代码
using System.Linq;
using System.Windows;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Media; namespace ToolsTest
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
} private void btnClick_Click(object sender, RoutedEventArgs e)
{
int _childCount = VisualTreeHelper.GetChildrenCount(this);
MessageBox.Show("MainPage下级子对象总数:" + _childCount.ToString());//就是一个Grid,所以返回1 IEnumerable<Button> AllButtons = FindChildren<Button>(this);//得到所有的Buttons int i =;
foreach (Button btn in AllButtons)
{
i++;
MessageBox.Show(string.Format("第{0}个按钮[{1}]的内容为:{2}",i,btn.Name,btn.Content));
} StackPanel sp = VisualTreeHelper.GetParent(btn2) as StackPanel;
MessageBox.Show(string.Format("{0}的上级对象是{1}",btn2.Content,sp.Name)); Rect rect = new Rect(, , , ); IEnumerable<UIElement> check = VisualTreeHelper.FindElementsInHostCoordinates(rect, this); //检测MainPage的0,0到100,25矩形区域内有哪些元素 foreach (UIElement item in check)
{
string _name = item.GetValue(NameProperty).ToString();
if (_name.Length > )
{
MessageBox.Show(_name);
}
}
} /// <summary>
/// FindChildren
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="parent"></param>
/// <returns></returns>
public IEnumerable<T> FindChildren<T>(DependencyObject parent) where T : class
{
var count = VisualTreeHelper.GetChildrenCount(parent);
if (count > )
{
for (var i = ; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
var t = child as T;
if (t != null)
yield return t; var children = FindChildren<T>(child);
foreach (var item in children)
yield return item;
}
}
}
}
}

参考博客地址:
http://www.cnblogs.com/yjmyzz/archive/2010/01/02/1638006.html

上一篇:QF——iOS代理模式


下一篇:应用层open(read、write、close)怎样调用驱动open(read、write、close)函数的?