
正文
WPF 查找控件的所有子控件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
/// <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) where T : DependencyObject
{
if (parent != null)
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = ; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child != null)
{
lstT.Add(child);
}
FindVisualChild<T>(v, ref lstT);
}
}
}
在DataGrid中查找选定行中的子控件使用实例:
private void ComboBox_SelectionChanged(object sender, 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)
{
//子控件的处理代码
}
}
}






