Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

Find a UI Automation Element for a List Item

This topic shows how to retrieve an AutomationElement for an item within a list when the index of the item is known.

Example

The following example shows two ways of retrieving a specified item from a list, one using TreeWalker and the other using FindAll.

The first technique tends to be faster for Win32 controls, but the second is faster for Windows Presentation Foundation (WPF) controls.

/// <summary>
/// Retrieves an element in a list, using TreeWalker.
/// </summary>
/// <param name="parent">The list element.</param>
/// <param name="index">The index of the element to find.</param>
/// <returns>The list item.</returns>
AutomationElement FindChildAt(AutomationElement parent, int index)
{
    if (index < 0)
    {
        throw new ArgumentOutOfRangeException();
    }
    TreeWalker walker = TreeWalker.ControlViewWalker;
    AutomationElement child = walker.GetFirstChild(parent);
    for (int x = 1; x <= index; x++)
    {
        child = walker.GetNextSibling(child);
        if (child == null)
        {
            throw new ArgumentOutOfRangeException();
        }
    }
    return child;
}

/// <summary>
/// Retrieves an element in a list, using FindAll.
/// </summary>
/// <param name="parent">The list element.</param>
/// <param name="index">The index of the element to find.</param>
/// <returns>The list item.</returns>
AutomationElement FindChildAtB(AutomationElement parent, int index)
{
    Condition findCondition = new PropertyCondition(AutomationElement.IsControlElementProperty, true);
    AutomationElementCollection found = parent.FindAll(TreeScope.Children, findCondition);
    if ((index < 0) || (index >= found.Count))
    {
        throw new ArgumentOutOfRangeException();
    }
    return found[index];
}

See Also

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.