一、查找某种类型的子控件,并返回一个List集合
public List
{
DependencyObject child = null;
List
for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if (child is T && (((T)child).GetType() == typename))
{
childList.Add((T)child);
}
childList.AddRange(GetChildObjects
}
return childList;
}
调用:
List
for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
{
child = VisualTreeHelper.GetChild(obj, i);
if (child is T && (((T)child).GetType() == name |string.IsNullOrEmpty(name)))
{
childList.Add((T)child);
}
childList.AddRange(GetChildObjects
}
return childList;
}
调用:
List
三、通过名称查找某子控件:
public T GetChildObject
{
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
if (grandChild != null)
return grandChild;
}
}
returnnull;
}
调用:
StackPanel sp = GetChildObject
四、通过名称查找父控件
public T GetParentObject
{
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);
}
returnnull;
}
调用:
Grid layoutGrid = VTHelper.GetParentObject