WPF 查找子控件的一个方法
/// <summary>
/// 查找子控件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="name"></param>
/// <returns></returns>
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;
}
List<Rectangle> recList = GetChildObjects<Rectangle>(stackPanel_rec1, ""); //此处调用
我的xaml大致格式为
<StackPanel>
<canvas>
<rectangle/>
</canvas>
<canvas>
<rectangle/>
</canvas>
</StackPanel>