WPF 从当前层次遍历查找 子控件及父控件

转自:https://www.cnblogs.com/Viper/p/3801495.html

SilverLight遍历父子控件的通用方法

想从SilverLight中DataGrid找元素,真是麻烦,没有Rows对象,无法遍历。从网上找来这些方法,挺好用的:

public class VTHelper()
{
    //GetParentObject方法,获取父控件方法。该方法将根据当前控件,遍历查找其父控件是否存在。参数1是表示当前子控件名,参数2是要查询父控件名;使用VisualTreeHelper.GetParent方法获取当前父控件。
        public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);

            while (parent != null)
            {
                if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)parent;
                }
                parent = VisualTreeHelper.GetParent(parent);
            }
            return null;
        }
    //GetChildObject,获取子控件方法。该方法将根据当前控件,遍历查找其子控件是否存在。参数1是表示当前父控件名,参数2是要查询子控件名;
        public T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject child = null;
            T grandChild = null;

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)child;
                }
                else
                {
                    grandChild = GetChildObject<T>(child, name);
                    if (grandChild != null)
                        return grandChild;
                }
            }
            return null;
        }
     //GetChildObjects方法,该方法将把所有子控件作为List集合返回到客户端。其中第一个参数是父控件参数,而第二个参数是特定子控件名称,如果需要遍历全部子控件,第二个参数留空即可。
        public List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement  
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
                {
                    childList.Add((T)child);
                }
                childList.AddRange(GetChildObjects<T>(child,""));
            }
            return childList;
        }
}

调用示例
private void btModifyChilds_Click(object sender, RoutedEventArgs e)
{
     Globals VTHelper = new Globals();
     List<TextBlock> textblock = VTHelper.GetChildObjects<TextBlock>(this.LayoutRoot, "");
     foreach (TextBlock tmpTextblock in textblock)
     {
          tmpTextblock.FontSize += 6;
     }
 }

  

  Type t = typeof(MyChild);

    bool 是否是某个的子类 = t.IsSubclassOf(typeof(MyBase));
    bool 是否是枚举 = t.GetProperty("TestState").PropertyType.IsEnum;
posted @ 2020-03-06 14:35  风中寻觅  阅读(774)  评论(0编辑  收藏  举报