Should I be using AutomationPeer or AutomationElement? Or both?

3.8k views Asked by At

I have just started using AutomationElement because we want to do integration testing of our custom controls, and I think I should be using AutomationElement.

I have successfully created a Window with a custom control in it, and can successfully obtain AutomationElements for both the window and control

  // Retrieve the View
  System.Windows.Automation.Condition viewCondition = new PropertyCondition(AutomationElement.AutomationIdProperty, "MyTestView");
  AutomationElement view = AutomationElement.RootElement.FindFirst(TreeScope.Children, viewCondition);
  Assert.IsNotNull(view);

  // Retrieve the CustomControl
  System.Windows.Automation.Condition comboboxCondition = new PropertyCondition(AutomationElement.AutomationIdProperty, "MyCustomControl");
  AutomationElement combobox = view.FindFirst(TreeScope.Children, comboboxCondition);
  Assert.IsNotNull(comboboxCondition);

Now, what I want to do is use, for example the ValuePattern. And this is where I become confused.

Looking for information, I searched the WPF source at referencesource.microsoft.com. I encountered ComboboxAutomationPeer, which implements IValueProvider, so now I'm confused.

Should I also implement MyCustomControlAutomationPeer that implements IValueProvider, and will AutomationElement then work with ValuePattern? Or should I have MyCustomControl implement IValueProvider?

1

There are 1 answers

6
Simon Mourier On

You don't have to implement anything to use a pattern. UI Automation does this for you (acting as a proxy for the target application). This is well explained in official documentation here: Get Supported UI Automation Control Patterns

Here is an example extract:

    SelectionItemPattern pattern;
    try
    {
        pattern = yourAutomationElement.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.Message);  // Most likely "Pattern not supported." 
        return;
    }
    pattern.Select();