How To: Get automation working properly on data bound WPF list or combo box

WPF makes it really easy to data bind properties of a control including the children collection of ItemsControl like ListBox, ComboBox, TreeView etc.  For example, for a list box, the user can easily bind the ItemsSource property.

When an ItemsControl is bound to a data source, the accessibility implementation of WPF uses the ToString() method to get the value of each item in the ItemsControl. If the data source is XML (or even if it is .NET class without proper ToString() method), this value is simply the string "System.Xml.XmlElement" (or similar format representing the class type) for all the items.

This means an automation tool cannot get an meaningful property for these items to search. If the automation tool records Name=System.Xml.XmlElement as the search criteria, then it will always playback the action on the first item irrespective of the which item the action was performed.  (For that matter, even the accessibility applications like Narrator will not give any meaningful property.)

The Coded UI Test recorder recognizes this problem and gives following error -

Last action on list item was not recorded because the control does not have any good identification property.

To fix the problem, you can do one of the two things in your product code -

  1. If the data binding is to .NET object(s) and you own the code for those .NET class(es) too, override the ToString() method to provide meaningful value.  This issue stems from the fact that the default ToString() of the System.Object simply returns the type of object as string like System.Xml.XmlElement.
  2. The other alternative is to bind the AutomationProperties.Name property of list item properly.

For example, adding the following code in bold corrects the problem for this List -

   <ListBox Name="GoodList" Grid.Column="1" Grid.Row="1"
           ItemsSource="{Binding Source={StaticResource Oscar2010},
                                 XPath=BestPictureNomination}">
       < ListBox.ItemContainerStyle ><br>          <Style ><br>              <Setter Property ="AutomationProperties.Name"                      Value="{Binding XPath
 =.}"/><br>          </Style ><br>      </ListBox.ItemContainerStyle > 
  </ListBox>

A complete sample XAML file with one bad list and one good list is here.

MainWindow.xaml