WPF枚舉指定類型控件

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章