查找所有子控件WPF
我想找到WPF控件中的所有控件。 我看了很多样本,看起来他们都需要将Name作为参数传递或者根本不起作用。
我有现有的代码,但它无法正常工作:
public static IEnumerable FindVisualChildren(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(child)) { yield return childOfChild; } } } }
例如,它不会在TabItem
获取DataGrid
。
有什么建议?
你可以使用这些。
public static List GetLogicalChildCollection (object parent) where T : DependencyObject { List logicalCollection = new List (); GetLogicalChildCollection(parent as DependencyObject, logicalCollection); return logicalCollection; } private static void GetLogicalChildCollection (DependencyObject parent, List logicalCollection) where T : DependencyObject { IEnumerable children = LogicalTreeHelper.GetChildren(parent); foreach (object child in children) { if (child is DependencyObject) { DependencyObject depChild = child as DependencyObject; if (child is T) { logicalCollection.Add(child as T); } GetLogicalChildCollection(depChild, logicalCollection); } } }
您可以在RootGrid中获取子按钮控件,如下所示:
List
您可以使用此示例:
public Void HideAllControl() { /// casting the content into panel Panel mainContainer = (Panel)this.Content; /// GetAll UIElement UIElementCollection element = mainContainer.Children; /// casting the UIElementCollection into List List < FrameworkElement> lstElement = element.Cast(); foreach (Control contol in lstControl) { ///Hide all Controls contol.Visibility = System.Windows.Visibility.Hidden; } }