使用UI Automation选择一行数据网格

本文关键字:一行 数据 数据网 网格 UI Automation 选择 使用 | 更新日期: 2023-09-27 18:21:48

我正在编写一个UI自动化软件。我需要在数据网格中选择一行,然后单击运行按钮。我尝试了互联网上的大多数示例代码,但它们对我不起作用。例如,选择网格视图行:

当我写以下代码时:

AutomationElement dataGrid =  this.mainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "2885"));
if (dataGrid != null)
{
    GridPattern pattern = GetGridPattern(dataGrid);
    AutomationElement tempElement = pattern.GetItem(1, 1);
    tempElement.SetFocus();
}

我收到错误:"目标元素无法接收焦点。"这与最后一行有关。

我也试过代码:

AutomationElement mainGrid = // find the grid in the window
var columnCount = (int)mainGrid.GetCurrentPropertyValue(GridPattern.ColumnCountProperty);
var mainGridPattern = (GridPattern)mainGrid.GetCurrentPattern(GridPattern.Pattern);
var rowToSelect = 2;
// select just the first cell
var item = mainGridPattern.GetItem(rowToSelect, 0);
var itemPattern = (SelectionItemPattern)item.GetCurrentPattern(SelectionItemPattern.Pattern);
itemPattern.Select();

但我和我收到了错误:"不支持的模式"。

我应该提到的是,我正在使用UISpy来检索元素属性。

你能解释一下出了什么问题,我应该如何选择一行吗?![UI Spy][1]

使用UI Automation选择一行数据网格

以下是如何做到这一点:

        // get to ROW X (here it's row #1 name is always "Row X")
        AutomationElement row1 = dataGrid.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Row 1"));
        // get row header
        AutomationElement row1Header = row1.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Header));
        // invoke it (select the whole line)
        ((InvokePattern)row1Header.GetCurrentPattern(InvokePattern.Pattern)).Invoke();

要找到这些操作,您可以使用UISpy并尝试树中的不同项目,查看每个项目实现的模式,然后使用UISpy上下文"控制模式"菜单进行尝试。