2011-04-28 27 views
6

¿cómo selecciono ComboBox's SelectedIndex = -1?seleccionando el elemento del cuadro combinado usando la automatización ui

me escribió un código para automatizar las pruebas:

AutomationElement aeBuildMachine = null; 
int count = 0; 
do 
{ 
    Console.WriteLine("\nLooking for Build Machine Combo Box"); 
    aeBuildMachine = aeTabitemmain.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "ListBoxItem")); 
    if (aeBuildMachine == null) 
      throw new Exception("No Build Machine Combo Box"); 
    else 
      Console.WriteLine("Found Build Machine Combo Box"); 
    ++count; 
} 
while (aeBuildMachine == null && count < 50); 

Console.WriteLine("Selecting Build machine from combobox..."); 
SelectionItemPattern spBuildmachine = (SelectionItemPattern)aeBuildMachine.GetCurrentPattern(SelectionItemPattern.Pattern); 

¿Cómo se utiliza este SelectionItemPattern?

Respuesta

1

http://msdn.microsoft.com/de-de/library/system.windows.automation.selectionitempattern_members(v=VS.85).aspx

Esa es la respuesta a su pregunta como lo entendía.

Pero ... ¿es realmente tu pregunta?

De todos modos, puede agregar o eliminar Elementos seleccionables de una selección que, supongo, pertenecen a su elemento primario, lo mismo ocurre con otras cosas como comprobar si están seleccionados.

+0

O http://msdn.microsoft.com/en-us/library/system.windows.automation.selectionitempattern_members%28v=vs.90 % 29.aspx si prefiere el inglés MSDN. – SteveWilkinson

17

Esto es aproximadamente 100 veces más complicado de lo que necesita, pero finalmente lo tengo funcionando. El gran problema con el WPF ComboBox es que, en lo que respecta a Automatización, no parece tener ningún ListItems hasta que se haya ampliado el ComboBox.

El siguiente código usa el patrón Expandir contraer para desplegar momentáneamente la lista y luego colapsarla, luego puede usar FindFirst en el ComboBox para seleccionar ListItem y luego usar el patrón SelectionItem para seleccionarlo.

En el caso de la pregunta original, una selección de -1 significa que no hay elementos seleccionados. No hay un método para esto, pero podría simplemente usar FindAll para obtener una colección de ListItems, obtener el patrón SelectionItem para cada uno por turno y llamar a su método RemoveFromSelection.

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; 
    } 
1

pensé que iba a compartir esto como una forma sencilla de seleccionar cualquier elemento de un cuadro combinado o en otro recipiente artículo:

protected AutomationElement GetItem(AutomationElement element, string item) 
    { 
     AutomationElement elementList; 
     CacheRequest cacheRequest = new CacheRequest(); 
     cacheRequest.Add(AutomationElement.NameProperty); 
     cacheRequest.TreeScope = TreeScope.Element | TreeScope.Children; 

     elementList = element.GetUpdatedCache(cacheRequest); 

     foreach (AutomationElement child in elementList.CachedChildren) 
      if (child.Cached.Name == item) 
       return child; 

     return null; 
    } 

elemento es el contenedor de cuadro combinado o un elemento, elemento es el nombre de la cadena o valor literal del artículo en el contenedor. Una vez que tenga el artículo, puede hacer lo siguiente para seleccionarlo:

protected void Select(AutomationElement element) 
    { 
     SelectionItemPattern select = (SelectionItemPattern)element.GetCurrentPattern(SelectionItemPattern.Pattern); 
     select.Select(); 
    } 

Espero que esto ayude a los demás. Derivé este patrón de la documentación de MSDN en la automatización, encontré aquí:

MSDN - Automation and Cached Children

+0

No estoy seguro de por qué, pero para mi proyecto, select.Select() lanzará una excepción si select es el elemento seleccionado actualmente. - Objetivo Win32 si eso hace la diferencia –

+0

Al utilizar la solicitud en caché lo hizo complejo. –

1

Creo que esto podría ser la forma más fácil para un simple valor ComobBox colocador genérica éste se proporciona bien los elementos de la lista en el doesn ComboBox no tienen duplicados

private void SetCombobValueByUIA(AutomationElement ctrl, string newValue) 
{ 
    ExpandCollapsePattern exPat = ctrl.GetCurrentPattern(ExpandCollapsePattern.Pattern) 
                   as ExpandCollapsePattern; 

    if(exPat== null) 
    { 
     throw new ApplicationException("Bad Control type..."); 
    } 

    exPat.Expand(); 

    AutomationElement itemToSelect = ctrl.FindFirst(TreeScope.Descendants, new 
          PropertyCondition(AutomationElement.NameProperty,newValue)); 

    SelectionItemPattern sPat = itemToSelect.GetCurrentPattern(
               SelectionItemPattern.Pattern) as SelectionItemPattern ; 
    sPat. Select(); 
} 
2

Esto es lo que funcionó para mí.

/// <summary> 
    /// Extension method to select item from comboxbox 
    /// </summary> 
    /// <param name="comboBox">Combobox Element</param> 
    /// <param name="item">Item to select</param> 
    /// <returns></returns> 
    public static bool SelectComboboxItem(this AutomationElement comboBox, string item) 
    { 
     if (comboBox == null) return false; 
     // Get the list box within the combobox 
     AutomationElement listBox = comboBox.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.List)); 
     if (listBox == null) return false; 
     // Search for item within the listbox 
     AutomationElement listItem = listBox.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, item)); 
     if (listItem == null) return false; 
     // Check if listbox item has SelectionItemPattern 
     object objPattern; 
     if (true == listItem.TryGetCurrentPattern(SelectionItemPatternIdentifiers.Pattern, out objPattern)) 
     { 
      SelectionItemPattern selectionItemPattern = objPattern as SelectionItemPattern; 
      selectionItemPattern.Select(); // Invoke Selection 
      return true; 
     } 
     return false; 
    } 

Uso

 AutomationElement paymentCombobox = element.FindFirst(
      TreeScope.Children, 
      new PropertyCondition(AutomationElement.NameProperty, "cbPayment") 
     ); 
     paymentCombobox.SelectComboboxItem("Cash"); 

recursos https://msdn.microsoft.com/en-us/library/ms752305(v=vs.110).aspx

+1

¿Puedes dejar algunos comentarios en el código para describir lo que hace tu código? – Shawn

1

No hay un gran cambio, pero sólo unos pocos a notar,

  1. No necesite utilizar patrón de colapso, llamar a expand hará el truco para ti.
  2. Usando treescope.subtree trabajó para mí en lugar de los niños.

El ejemplo de código sería así,

public static void SelectValueInComboBox(string comboBox, string value) 
{ 
    var comboBoxElement = HelperMethods.FindElementFromAutomationID(comboBox); 
    if (comboBoxElement == null) 
     throw new Exception("Combo Box not found"); 

    ExpandCollapsePattern expandPattern = (ExpandCollapsePattern)comboBoxElement.GetCurrentPattern(ExpandCollapsePattern.Pattern); 

    AutomationElement comboboxItem = comboBoxElement.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, value)); 

    SelectionItemPattern selectPattern = (SelectionItemPattern)comboboxItem.GetCurrentPattern(SelectionItemPattern.Pattern); 
    selectPattern.Select(); 
} 
Cuestiones relacionadas