从数据网格AutomationUI中检索单元格内容

时间:2017-09-03 18:15:05

标签: c# wpf ui-automation

非常简单,尝试在某一行中的每个单元格中获取数据。 代码示例(请阅读评论)

//Get Main window
AutomationElement prog = AutomationElement.RootElement.FindFirst(TreeScope.Children,
  new PropertyCondition(AutomationElement.NameProperty, mainTitle));
//Get data grid
var datagrid = prog.FindFirst(TreeScope.Children,
  new PropertyCondition(AutomationElement.AutomationIdProperty, "AccountGrid"));

//get rows (returns the correct value)
var rows = datagrid.FindAll(TreeScope.Descendants,
  new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem));

foreach (AutomationElement row in rows)
{
  //Is NOT null and returns 5, as the number of cells in each row
  var findRow = row.FindAll(TreeScope.Children,
      new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom));
  Console.WriteLine("Is findrow null ?: " + (findRow == null) + "cell count: " + findRow.Count);

  for (int i = 0; i < findRow.Count -1; i++)
  {
      //cache request
      var cacheRequest = new CacheRequest
      {
          AutomationElementMode = AutomationElementMode.None,
          TreeFilter = Automation.RawViewCondition
      };
      cacheRequest.Add(AutomationElement.NameProperty);
      cacheRequest.Add(AutomationElement.AutomationIdProperty);
      cacheRequest.Push();
      //Could be a problem with the propertyname?
      var cellText = findRow[i].FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "Profile"));
      //RETURNS NULL!
      Console.WriteLine("Is cellText null? " + (cellText == null));
      cacheRequest.Pop();
      Console.WriteLine(cellText.Cached.Name);
  }
}

基本上你可以看到,我可以很容易地得到行数,每行中的单元格数量,但是当它检索到单元格数据时,它会返回null。它可能是缓存问题吗?

(抱歉我的格式化)

1 个答案:

答案 0 :(得分:0)

所以经过一些修补,我发现我实际上并不需要推高速缓存,我可以直接推出一个单元格:

try
{
    AutomationElement prog = AutomationElement.RootElement.FindFirst(TreeScope.Children,
        new PropertyCondition(AutomationElement.NameProperty, "Window Title"));
    var datagrid = prog.FindFirst(TreeScope.Children,
        new PropertyCondition(AutomationElement.AutomationIdProperty, "Your grid"));
    var rows = datagrid.FindAll(TreeScope.Children,
        new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem));
    foreach (AutomationElement row in rows)
    {
        var findRow = row.FindAll(TreeScope.Children,
            new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom));
        Console.WriteLine("===============");
        Console.WriteLine(findRow[1].Current.Name);
    }

    Console.WriteLine("===============");
}
catch (Exception e)
{
    Console.WriteLine(string.Format("{0}{1}", e.Message,
        " At Line:" + e.StackTrace.Substring(e.StackTrace.LastIndexOf(' '))));
}
Console.ReadLine();

这将获得每行的第二个单元格。