WPF 查找控件的父级和子级控件

2016-08-20 10:37:40来源:http://zhaolb.blog.51cto.com/6455043/1543401作者:zhaoliubin人点击


1、查找当前控件的父级:

①、例如:FrameworkElement frame=(FrameworkElement)this.Parent;

②、通过当前控件的Name来查找

例如:<Border x:Name="BorderListboxItem" />

/// <summary>

/// 获取父级控件

/// </summary>

/// <typeparam name="T">类型</typeparam>

/// <param name="obj">当前控件的Name</param>

/// <param name="name">要查找的父级控件的Name(Name为“ ”时,表示上一次父控件)</param>

/// <returns></returns>

public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement

{

DependencyObject parent = VisualTreeHelper.GetParent(obj);

int i = 0;

while (parent != null)

{

if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))

{

return (T)parent;

}

parent = VisualTreeHelper.GetParent(parent);

}

return null;

}

Border bd=GetParentObject<Border>(this.BorderListboxItem," ");

2、查找当前控件的子集控件:

例如:

/// <summary>

/// 获取当前控件的子集控件

/// </summary>

/// <typeparam name="T">类型</typeparam>

/// <param name="root">当前父级控件的Name</param>

/// <returns></returns>

static T FindChildOfType<T>(DependencyObject root) where T : class

{

var queue = new Queue<DependencyObject>();

queue.Enqueue(root);

while (queue.Count > 0)

{

DependencyObject current = queue.Dequeue();

for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)

{

var child = VisualTreeHelper.GetChild(current, i);

var typedChild = child as T;

if (typedChild != null)

{

return typedChild;

}

queue.Enqueue(child);

}

}

return null;

}


最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台