Bose_geek
Bose_geek

Reputation: 498

Simple- How To select an Item from a WPF combo box using coded UI

I have worked with coded UI for web applications but for the first time I am trying to leverage Coded UI for WPF. I want to perform a click on an item from a combobox But, I am unable to achieve the same here in WPF. I tried to loop through the items inside the combo box but It did not work. Tried with Search Property - No result. Also, was trying to figure out the AutomationElement stuff but not able to get a solution. It would be great if I can get an idea of the approach that needs to be followed to achieve the requirement.

I have captured the controls and want to play around with them. No record and playback.

Upvotes: 0

Views: 4175

Answers (2)

kida
kida

Reputation: 501

You can use the WpfComboBox's SelectedItem property which takes the name of the item you want to select (as mentioned in my comment in yonder answer)

var myComboBox = this.UIMap.UIMainWindowWindow.UIItemComboBox;
var items = myComboBox.Items;
myComboBox.SelectedItem = items[0].Name;

or you can simply set the SelectedIndex if you already know the index of the item you want to set

var myComboBox = this.UIMap.UIMainWindowWindow.UIItemComboBox;
var items = myComboBox.Items;
myComboBox.SelectedIndex = 0;

or you can first click the combobox to get it expanded and then get the UITestControl for the item element and perform a click on it (unfortunately you have to manually click the combobox because it seems that the ExpandWhileSearching configuration it doesn't work on it)

var myComboBox = this.UIMap.UIMainWindowWindow.UIItemComboBox;
var items = myComboBox.Items;
Mouse.Click(myComboBox);
Mouse.Click(items[0]);

or

var myComboBox = this.UIMap.UIMainWindowWindow.UIItemComboBox;
var items = myComboBox.Items;
myComboBox.Expanded = true;
Mouse.Click(items[0]);

Upvotes: 5

Ryan Cox
Ryan Cox

Reputation: 958

You would create the combobox object the same way you would in Html, just using Microsoft.VisualStudio.TestTools.UITesting.WpfControls namespace. For example:

public WpfComboBox tester
{
    get
    {
        WpfComboBox target = new WpfComboBox();
        return target;
    }
}

Then, you will create a UITestControlCollection object to store the .Items of the combo box.

UITestControlCollection comboBoxItems = tester.Items;

From here, you should be able to edit and set selected items ( tester.SelectedItem = comboBoxItems[0].ToString();) at will.

Upvotes: 0

Related Questions