public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
}
public static IEnumerable<T> FindLogicalChildren<T> (DependencyObject depObj)where T: DependencyObject
{
if (depObj != null)
{
foreach (object rawChild in LogicalTreeHelper.GetChildren(depObj))
{
if (rawChild is DependencyObject)
{
if (rawChild is T)
{
yield return (T)rawChild;
}
foreach (T childOfChild in FindLogicalChildren<T>((DependencyObject)rawChild))
{
yield return childOfChild;
}
}
}
}
}
摘自https://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type