1

今天我正在学习.NET UI自动化框架。所以到目前为止我所做的(指各种文章)事件不会触发listbox项目选择 - .Net UIAutomation框架

  1. 有一个WinForm的Listbox,PictureBox,TextBox和Button控件。请参阅图片:WinForm to be tested

  2. 我有一个控制台应用程序,它具有所有UI自动化测试脚本或代码,可以自动进行winform UI测试。

工作: 一旦从列表框中选择项目,图片框加载一些图像,并显示它(加载代码是在列表框的SelectedIndexChanged事件)。

下面是窗体列表框控件的代码:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     textBox1.BackColor = Color.White; 
     pictureBox1.Image = imageCollection.ElementAtOrDefault(listBox1.SelectedIndex); 
     textBox1.Text = pictureBox1.Image.GetHashCode().ToString(); 
     this.Refresh(); 
    } 

现在我UIAutomation测试脚本代码如下所示:(只显示必要的部分)

 AutomationElement listBoxElement = mainFormWindowElement.FindFirst(TreeScope.Children, 
      new PropertyCondition(AutomationElement.AutomationIdProperty, "listBox1")); 

     Assert.IsNotNull(listBoxElement, "Cant find the listbox element"); 

     AutomationElementCollection listBoxItems = 
      listBoxElement.FindAll(TreeScope.Children,new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.ListItem)); 

     AutomationElement itemToSelectInListBox = listBoxItems[new Random().Next(0, listBoxItems.Count - 1)]; 

     Object selectPattern = null; 

     if (itemToSelectInListBox.TryGetCurrentPattern(SelectionItemPattern.Pattern, out selectPattern)) 
     { 
      (selectPattern as SelectionItemPattern).AddToSelection(); 
      (selectPattern as SelectionItemPattern).Select(); 

     } 

执行代码后, Select()方法确实起作用,并且如下所示选择表单列表框项目 :enter image description here

正如您在图像,列表框项目被选中,但事件SelectedIndexChange没有被激发,并且图框不反映更改。

所以任何指针是有很大帮助:)

感谢

+0

我不知道是什么问题,但你可以通过添加'listbox1_selectedIndexChanged一个临时的解决方法(NULL,NULL);'会后声明'AutomationElement itemToSelectInListBox = listBoxItems [新的随机()和Next(0, listBoxItems.Count - 1)]; ' – Marshal

+0

正如我所说,这个自动化用户界面API是在一个consoleapp(另一个项目和exe文件)和窗体是在另一个。我所能做的唯一方法就是使用relfection API。但是,如果我这样做,它将是完全不同的实例,根本没有连接。 – Zenwalker

回答

1

@zenwalker 是列表的数据绑定填充?如果是的话,有一个机会选择事件不会发生。你能分享将数据绑定到列表框的代码吗?为了回答这个问题抱歉,我没有足够的代表来添加评论。

或者你可以参考下面的SO文章,看看我们如何能做到数据绑定列表框Winforms, databinding, Listbox and textbox

+0

不,我在设计时自己手动添加了列表框的内容。所以我没有在这里使用任何数据绑定的上下文。谢谢:) – Zenwalker

1

这工作如果selectionMode是改变为MultiSimple。我不知道为什么会发生这种情况。 但是,如果SelectionMode是One,selectedIndexevent不会被触发。

+1

试过双方,死路一条! – Zenwalker

0

事件SelectedIndexChanged未被触发,而SelectionMode被设置为单个或一个。

请确保您更新图片框也同时SelectionChanged事件被触发

1

也许有点晚,但我还是希望这将有助于人:

我有完全相同的问题。能够通过点击鼠标来触发事件。对于下面的代码,您将需要对Microsoft.TestAPI(http://www.nuget.org/packages/Microsoft.TestApi/0.6.0)的引用,但还有其他方法可以模拟点击。

static AutomationElement SelectItem(AutomationElement item) 
    { 
     if (item != null) 
     { 
      ((SelectionItemPattern)item.GetCurrentPattern(SelectionItemPattern.Pattern)).Select(); 
      System.Windows.Point point = item.GetClickablePoint(); 
      Microsoft.Test.Input.Mouse.MoveTo(new System.Drawing.Point((int)point.X, (int)point.Y)); 
      Microsoft.Test.Input.Mouse.Click(MouseButton.Left); 
     } 

     return item; 
    } 
相关问题