GridPattern控件模式用于支持可充当子元素集合的容器的控件。该元素的子级必须实现IGridItemProvider,而且必须在可以按行和列进行遍历的二维逻辑坐标系中进行组织。支持GridPattern的最常见的控件为GridView,在WPF中使用ListView和GridView组合即可得到相应的GridView。
GridPattern的方法:GetItem
此方法有两个参数,即DataGrid的Row和Column。通过GridPattern的GetItem方法可以获取DataGrid的某个确定的单元格,进而对单元进行操作。对单元格的操作主要有以下几个方面:
· 编辑单元格中的数据;
· 获取单元格中的数据;
· 获取单元格中嵌套的AutomationElement(一般用于自定义控件中
GridPattern的属性
GridPattern的Current属性中有如下两个属性:
· RowCount属性:GridPattern二维表格的行数。
· ColumnCount属性:GridPattern二维表格列数。
示例:
public static void TestGridPattern()
{
Process adressbook = Process.Start(@"C:/Program Files/Outlook Express/wab.exe");
Thread.Sleep(2000);
//Get main window "Address Book - Main Identity"
AutomationElement addresswindow = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Address Book - Main Identity"));
Thread.Sleep(2000);
//Get data grid "9001"
AutomationElement dategrid=addresswindow.FindFirst(TreeScope.Descendants,new PropertyCondition(AutomationElement.AutomationIdProperty,"9001"));
Thread.Sleep(2000);
GridPattern dategridpattern=Utility.UIA.ControlPattern.Gridpattern.GetGridPattern(dategrid);
AutomationElement item1 = dategridpattern.GetItem(2, 0);
Console.WriteLine("cell which row='{0}',column='{1}',cell value is '{2}'", 2, 0, item1.Current.Name);
Console.WriteLine("Grid row count='{0}',column count='{1}'",dategridpattern.Current.RowCount,dategridpattern.Current.ColumnCount);
}
public class Gridpattern
{
public static GridPattern GetGridPattern(AutomationElement element)
{
object currentPattern;
if (!element.TryGetCurrentPattern(GridPattern.Pattern, out currentPattern))
{
throw new Exception(string.Format("Element with AutomationID '{0} and Name '{1}' does not support the GridPattern.", element.Current.AutomationId, element.Current.Name));
}
return currentPattern as GridPattern;
}
}