我正在尝试使用 WPF UI 自动化工作而不使用虚假的 thread.sleep 语句。我想做的是有一个函数 GetElementById 不断轮询,直到控件可用(或发生超时)。问题是它似乎缓存了我的父元素的子控件。是否可以刷新儿童?或者有人有替代方法吗?
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;
}