Search code examples
c#microsoft-ui-automation

Selecting drop down using UI Automation does not keep drop down expanded


I'm attempting to select a drop down menu, so that I can select a Courier Service using Microsoft UI Automation.

Below is the code in which I'm using

public void SelectCourierService(string courierService)
{
        Console.WriteLine(@"SelectCourierService(" + courierService + @")");

        var expandCollapsePattern = (ExpandCollapsePattern)_courierServiceCombo.GetCurrentPattern(ExpandCollapsePatternIdentifiers.Pattern);
        expandCollapsePattern.Expand();
        expandCollapsePattern.Collapse();

        var listItem = _courierServiceCombo.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, courierService));
        listItem = AutomationElementHelper.GetSubtree(_courierServiceCombo, courierService);

        object selectionItemPattern;
        if (listItem.TryGetCurrentPattern(SelectionItemPattern.Pattern, out selectionItemPattern))
        {
            var selectPattern = (SelectionItemPattern)selectionItemPattern;
            selectPattern.Select();
        }

        Thread.Sleep(100);
 }

However when it gets to the following piece of code:-

expandCollapsePattern.Expand();

The UI drop down menu expands down but then collapses back up meaning that I cannot select the items in the drop down.

I was wondering if anyone has had the same problem and what they did to solve this.

Thanks


Solution

  • One of my work collegues found an answer to this solution and I have placed it below and this worked for me:-

    public static void SelectDropdownItem(AutomationElement dropdownBox, string itemToSelect, bool navigateToParent = true)
    {
            var expandCollapsePattern = (ExpandCollapsePattern)dropdownBox.GetCurrentPattern(ExpandCollapsePatternIdentifiers.Pattern);
            expandCollapsePattern.Expand();
            expandCollapsePattern.Collapse();
    
            var listItem = dropdownBox.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, itemToSelect));
    
            if (navigateToParent)
            {
                var controlViewWalker = TreeWalker.ControlViewWalker;
                listItem = controlViewWalker.GetParent(listItem);
            }
    
            object selectionItemPattern;
            if (listItem.TryGetCurrentPattern(SelectionItemPattern.Pattern, out selectionItemPattern))
            {
                var selectPattern = (SelectionItemPattern)selectionItemPattern;
                selectPattern.Select();
            }
    }