我在一个页面上有许多 HTMLDIV,我正在尝试使用
UIElement.getProperty("InnerText")
问题是我永远不知道 DIV 会有多少个孩子,以及元素会有多少级。 因此,我认为递归适用于这种情况,而不是嵌套的FOREACH语句。 但是,由于我的 DIVS 没有填充 .NAME 属性并且.GetType
始终是"HTMLDIV",我不知道如何访问子元素的.Innertext
。 我打算使用这种类型的方法:
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;
}
但我想我需要这样的东西:
if (child != null && child.innerText == strMyInnerText)
我希望一切都有意义。
在一个地方,我使用了基于下面的代码。它查找所有InnerText
项。
someControl.SearchProperties.Add("InnerText", "", PropertyExpressionOperator.Contains);
UITestControlCollection colNames = someControl.FindMatchingControls();
在我使用的另一个地方:
string s = ""; // In case there is no InnerText.
try
{
s = control.GetProperty("Text").ToString();
}
catch ( System.NotSupportedException )
{
// No "InnerText" here.
}
GetProperty 没有记录该异常,我想我在调用没有InnerText
的控件上的方法时发现了它。我找不到任何TryGetPropertyMethod
,但很容易写你自己的。
我还使用基于此递归例程的代码来访问层次结构中的所有控件。
private void visitAllChildren(UITestControl control, int depth)
{
UITestControlCollection kiddies = control.GetChildren();
foreach ( UITestControl kid in kiddies )
{
if ( depth < maxDepth )
{
visitAllChildren(kid, depth + 1);
}
}
}