/// <summary> ///查找子控件 /// </summary> /// <typeparam name="T">控件类型</typeparam> /// <param name="parent">父控件依赖对象</param> /// <param name="lstT">子控件列表</param> public static void FindVisualChild<T>(DependencyObject parent, ref List<T> lstT) whereT : DependencyObject { if (parent != null) { T child = default(T); int numVisuals =VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < numVisuals; i++) { Visual v =(Visual)VisualTreeHelper.GetChild(parent, i); child = v asT; if (child != null) { lstT.Add(child); } FindVisualChild<T>(v, reflstT); } } }
在DataGrid中查找选定行中的子控件使用实例:
private void ComboBox_SelectionChanged(objectsender, SelectionChangedEventArgs e) { DataGridRow currentRow = (DataGridRow)dgdRel.ItemContainerGenerator.ContainerFromIndex(dgdRel.SelectedIndex); //获取当前行 if (currentRow != null) { List<Control> lstControl = new List<Control>(); FormDispose.FindVisualChild<Control>(currentRow, ref lstControl); //获取当前行内所有的控件 if (lstControl != null) { //子控件的处理代码} } }