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

时间:2013-07-10 18:52:58

标签: c# datagrid ui-automation microsoft-ui-automation

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

当我写下面代码时:

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();

但我和我收到错误:“不支持的模式”。

我应该提一下,我正在使用UI Spy来检索元素属性。

你能解释一下我的错误吗?我应该如何选择一行? ![UI间谍] [1]

1 个答案:

答案 0 :(得分:2)

以下是如何做到这一点:

        // 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上下文“控制模式”菜单进行尝试。