This is about 100 times more complicated than it should be, but I finally got his job. The big problem with WPF ComboBox is that, as far as Automation is concerned, it does not have any ListItems until the ComboBox is expanded .
The following code uses the ExpandCollapse pattern for a short-term drop-down list, and then collapse it, then it can use FindFirst in the ComboBox to select the ListItem, and then use the SelectionItem pattern to select it.
In the case of the original question, a choice of -1 means that no items are selected. There is no way to do this, but you can just use FindAll to get the ListItems collection, get the SelectionItem template for each of them in turn and call its RemoveFromSelection method.
public static void SetSelectedComboBoxItem(AutomationElement comboBox, string item) { AutomationPattern automationPatternFromElement = GetSpecifiedPattern(comboBox, "ExpandCollapsePatternIdentifiers.Pattern"); ExpandCollapsePattern expandCollapsePattern = comboBox.GetCurrentPattern(automationPatternFromElement) as ExpandCollapsePattern; expandCollapsePattern.Expand(); expandCollapsePattern.Collapse(); AutomationElement listItem = comboBox.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, item)); automationPatternFromElement = GetSpecifiedPattern(listItem, "SelectionItemPatternIdentifiers.Pattern"); SelectionItemPattern selectionItemPattern = listItem.GetCurrentPattern(automationPatternFromElement) as SelectionItemPattern; selectionItemPattern.Select(); } private static AutomationPattern GetSpecifiedPattern(AutomationElement element, string patternName) { AutomationPattern[] supportedPattern = element.GetSupportedPatterns(); foreach (AutomationPattern pattern in supportedPattern) { if (pattern.ProgrammaticName == patternName) return pattern; } return null; }
source share