问题
I have a number of HTMLDIV on a page and I am trying to locate a particular one using the
UIElement.getProperty("InnerText")
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)
I hope that all makes sense.
回答1:
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.
}
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);
}
}
}
来源:https://stackoverflow.com/questions/22797785/recursively-locating-a-uielement-with-innertext-in-c-sharp