在UWP页面中查找所有TextBox控件

我需要找到UWP页面上但没有运气的所有TextBox。 我认为这将是Page.Controls上的一个简单的foreach,但这不存在。

使用DEBUG我可以看到,例如,一个网格。 但是我必须首先将Page.Content转换为Grid才能看到Children集合。 我不想这样做,因为它可能不是页面根目录中的网格。

先感谢您。

更新:这与’按类型查找WPF窗口中的所有控件’不同。 那是WPF。 这是UWP。 它们是不同的。

你快到了! 将Page.Content转换为UIElementCollection,这样您就可以获得Children集合并且是通用的。

如果element是UIElement,那么你必须使你的方法递归并查找Content属性,或者如果element是UIElementCollection,则查找子元素。

这是一个例子:

void FindTextBoxex(object uiElement, IList foundOnes) { if (uiElement is TextBox) { foundOnes.Add((TextBox)uiElement); } else if (uiElement is Panel) { var uiElementAsCollection = (Panel)uiElement; foreach (var element in uiElementAsCollection.Children) { FindTextBoxex(element, foundOnes); } } else if (uiElement is UserControl) { var uiElementAsUserControl = (UserControl)uiElement; FindTextBoxex(uiElementAsUserControl.Content, foundOnes); } else if (uiElement is ContentControl) { var uiElementAsContentControl = (ContentControl)uiElement; FindTextBoxex(uiElementAsContentControl.Content, foundOnes); } else if (uiElement is Decorator) { var uiElementAsBorder = (Decorator)uiElement; FindTextBoxex(uiElementAsBorder.Child, foundOnes); } } 

然后用以下方法调用该方法:

  var tb = new List(); FindTextBoxex(this, tb); // now you got your textboxes in tb! 

您还可以使用VisualTreeHelper文档中的以下genric方法来获取给定类型的所有子控件:

 internal static void FindChildren(List results, DependencyObject startNode) where T : DependencyObject { int count = VisualTreeHelper.GetChildrenCount(startNode); for (int i = 0; i < count; i++) { DependencyObject current = VisualTreeHelper.GetChild(startNode, i); if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T)))) { T asType = (T)current; results.Add(asType); } FindChildren(results, current); } } 

它基本上递归地获取当前项的子项,并将与所请求类型匹配的任何项添加到提供的列表中。

然后,您只需要在某个地方执行以下操作即可获取元素:

 var allTextBoxes = new List(); FindChildren(allTextBoxes, this); 

在我看来,你可以像在WPF中那样做。 因为UWP大多使用与WPF相同的XAML。

所以,请查看有关WPF相同问题的答案