【问题标题】:Recursively locating a UIElement with InnerText in C#在 C# 中使用 InnerText 递归定位 UIElement
【发布时间】:2014-04-01 22:02:54
【问题描述】:

我在一个页面上有许多 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)

我希望一切都有意义。

【问题讨论】:

    标签: c# coded-ui-tests


    【解决方案1】:

    在一个地方,我使用了基于以下代码的代码。它会找到所有 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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多