Silverlight的:查找在布局类型的所有控件 [英] Silverlight: Find all controls of type in layout

查看:161
本文介绍了Silverlight的:查找在布局类型的所有控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可靠的方法来构建的&LT控制列表;类型>包含在特定<面板>导出的控制 - 包括那些直接的孩子,那些是儿童等儿童上。

I'm looking for a reliable method to build a list of controls of <Type> contained in a specific <Panel> derived control - this includes those that are direct children, and those which are children of children and so on.

最明显的方法就是只是做递归:
添加到列表这种控制中任何子女;类型>,然后重复功能,这种控制是任何孩子&LT;面板>或后代

The most obvious way was to just do it recursively:
Add to list any children of this control of <Type>, then repeat function for any child of this control which is a <Panel> or descendant.

不过,我很担心,这不会在树中寻找所有控件 - 任何ContentControl中也可能包含℃的控制;类型>,则有可能HeaderedContentControl或其他任何类似的控制与一个或一个以上的孩子/内容属性

However I'm concerned that this won't find all controls in the tree - any ContentControl could also contain of a control of <Type>, as could HeaderedContentControl or any other similar control with one or more child/content attributes.

有执行与实际布局树搜索的任何手段,使的任意的控制没有包含特定父特定类型的实例都可以找到?

Is there any means of executing a search against the actual layout tree, so that any instance of a specific type of control contained without a specific parent can be found?

推荐答案

下面是一个相当幼稚的扩展方法: -

Here is a fairly naive extension method:-

public static class VisualTreeEnumeration
{
   public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
   {
     int count = VisualTreeHelper.GetChildrenCount(root);
     for (int i=0; i < count; i++)
     {
       var child = VisualTreeHelper.GetChild(root, i);
       yield return child;
       foreach (var descendent in Descendents(child))
         yield return descendent;
     }
   }
}

此方法确实有拉回,它不承担任何变化发生在树中的成员,而其正在进行中。这可以通过使用了ToList()来减轻在使用

This approach does have the draw back that it assumes no changes happen in the tree membership while its in progress. This could be mitigated in use by using a ToList().

现在,你可以使用效果的要求,LINQ: -

Now you can effect your requirements using LINQ:-

 var qryAllButtons = myPanel.Descendents().OfType<Button>();

这篇关于Silverlight的:查找在布局类型的所有控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆