Question

I am trying to use WPF UI Automation working without using spurious thread.sleep statements. What I would like to do is have a function GetElementById that continually polls until the control is available (or a timeout occurs). The problem is that it appears to cache the child controls of my parent element. Is it possible to refresh to Children? Or does anyone have an alternative approach?

public AutomationElement GetElementById(string id, int timeout)
{
    if (timeout <= 1000) throw new ArgumentException("Timeout must be greater than 1000", "timeout");

    AutomationElement element = null;

    int timer = 0;
    const int delay = 100;

    do
    {       
        element = MainWindow.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, id));                
        Thread.Sleep(delay);
        timer += delay;
    } while (element == null && timer < timeout);

    if (element == null) throw new InvalidOperationException("Unable to find element with id: " + id);

    return element;
}
Was it helpful?

Solution

If there is a better way than judicious use of Thread.Sleep, I've yet to find it.

UIAutomation does provide Events, and I guess that you could (to use your case as an example) listen for the event that occurs when the TabItem is selected, and only then continue to find the item by Id. But I suspect that this kind of pattern would play havoc with the overall readability of your code.

OTHER TIPS

The DoEvents function that is available in System.Windows.Forms.Application namespace is used to enable the UI to update while a long running process is occuring. It is not a member of the WPF namespaces. You can use something sililar by implementing it yourself as in this article or importing the System.Windows.Forms namespace and calling Application.DoEvents. This will allow your other processing to continue while you are doing your polling. It is a function to be used with caution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top