BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Selection Controls - ComboBox

The seventy-second part of the Windows Presentation Foundation Fundamentals tutorial looks further at the WPF selection controls. This article examines the ComboBox control, which combines a text box with an expandable list.

Altering the Drop-Down List Behaviour

The expandable list appears when the arrow at the side of the control is clicked and disappears when the control loses the focus, the arrow is clicked again or the text area of the control is clicked. You can change this third behaviour with the StaysOpenOnEdit property. If you set this property to true, the list is not hidden when the user clicks into the editing area.

To demonstrate, change the value of the property by editing the RAM ComboBox's XAML:

<ComboBox Name="RamBox" IsEditable="True" StaysOpenOnEdit="True">
    <ComboBoxItem>16GB</ComboBoxItem>
    <ComboBoxItem>32GB</ComboBoxItem>
    <ComboBoxItem>64GB</ComboBoxItem>
</ComboBox>

Run the program again to see the change in the behaviour of the list.

ComboBox Events

ComboBoxes inherit many events from the Selector class and its base classes. In addition, the ComboBox class defines two extra events. These are DropDownOpened and DropDownClosed. Unsurprisingly, these are raised when the user expands the list of items and when that list is hidden.

To demonstrate, let's capture the DropDownOpened event. We'll clear the Text property to empty the text box part of the control whenever the user opens the list. Start by registering the event in the control's XAML, as follows:

<ComboBox Name="RamBox"
          IsEditable="True"
          DropDownOpened="RamBox_DropDownOpened">
    <ComboBoxItem>16GB</ComboBoxItem>
    <ComboBoxItem>32GB</ComboBoxItem>
    <ComboBoxItem>64GB</ComboBoxItem>
</ComboBox>

Add the following method behind the window to clear the text box when the event is raised.

private void RamBox_DropDownOpened(object sender, EventArgs e)
{
    RamBox.Text = "";
}

Run the program for a final time to see the results. Type some text into the editable part of the ComboBox before clicking the arrow to expand the list. You should see that the text you entered is removed.

19 June 2014