This is about 100 times more complicated than it needs to be, but I finally got it working. The big issue with the WPF ComboBox is that as far as Automation goes, it doesn't appear to have any ListItems until the ComboBox has been expanded.
The following code uses the ExpandCollapse pattern to momentarily drop down the list and then collapse it, then it can use FindFirst on the ComboBox to get the ListItem to be selected, and then use the SelectionItem pattern to select it.
In the case of the original question, a selection of -1 means no items selected. There is no method for this, but you could simply use FindAll to get a collection of ListItems, get the SelectionItem pattern for each one 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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…