在C#中使用InnerText递归查找UIElement [英] Recursively locating a UIElement with InnerText in C#
问题描述
我在页面上有许多HTMLDIV,并且尝试使用
I have a number of HTMLDIV on a page and I am trying to locate a particular one using the
UIElement.getProperty("InnerText")
问题是我不知道DIV将有多少个孩子,有多少个将元素降级。因此,尽管递归适用于这种情况,而不是嵌套的FOREACH语句。但是由于我的DIVS没有填充.NAME属性,并且 .GetType
始终是'HTMLDIV',所以我不知道如何访问。
子元素。我将使用这种类型的方法:
The problem is I never know how many children the DIV will have and how many levels down the element will be. So I though recursion would work for this situation rather than nested FOREACH statements. However as my DIVS do not have a .NAME property populated and .GetType
is always 'HTMLDIV' I don't know how to access the .Innertext
of the child element. I was going to use this type of method:
ControlTypeIWantToFind result =
FindVisualChild<ControlTypeIWantToFind>(myPropertyInspectorView);
public static T FindVisualChild<T>(DependencyObject depObj, string strMyInnerText) 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)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}
但是我想我需要这样的东西:
But I think I need something like this:
if (child != null && child.innerText == strMyInnerText)
我希望一切都说得通。
推荐答案
在我曾经使用过的地方基于以下代码。它会找到所有 InnerText
项。
In one place I used code based on that below. It finds all InnerText
items.
someControl.SearchProperties.Add("InnerText", "", PropertyExpressionOperator.Contains);
UITestControlCollection colNames = someControl.FindMatchingControls();
在另一个地方,我使用了:
In another place I used:
string s = ""; // In case there is no InnerText.
try
{
s = control.GetProperty("Text").ToString();
}
catch ( System.NotSupportedException )
{
// No "InnerText" here.
}
该异常未记录在 GetProperty ,我想我在对确实执行此操作的控件上调用该方法时发现了它没有 InnerText
。我找不到任何 TryGetPropertyMethod
,但是编写自己的代码很容易。
The exception is not documented with GetProperty, I think I found it when calling the method on controls that did not have an InnerText
. I could not find any TryGetPropertyMethod
, but it would be easy to write your own.
我还使用了基于此递归例程的代码来访问层次结构中的所有控件。
I also used code based on this recursive routine to visit all the controls in the hierarachy.
private void visitAllChildren(UITestControl control, int depth)
{
UITestControlCollection kiddies = control.GetChildren();
foreach ( UITestControl kid in kiddies )
{
if ( depth < maxDepth )
{
visitAllChildren(kid, depth + 1);
}
}
}
这篇关于在C#中使用InnerText递归查找UIElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!