Share via


Improving the performance of the ComboBox

This has been discussed in some of the forums and other blogs, but I figured it was worth repeating. If you’ve ever tried to add thousands of items to a ComboBox, you probably noticed that when you run the program and click the button to open the ComboxBox’s dropdown, it takes several seconds for the dropdown to appear. This reason for the delay is that by default, the ComboBox uses a StackPanel, and a visual that represents each item is created at the same time, which is processor-intensive and memory-intensive.

It’s really easy to rectify this, though. Thanks to the fact that the ComboBox uses an ItemsPresenter, you can use the ItemsPanel property to change the panel that displays the items in the ComboBox. The VirtualizingStackPanel is an excellent candidate for this scenario. The VirtualizingStackPanel calculates the number of visible items, and a visual is created only for the items that are visible, so the dropdown promptly appears the user opens it.

The following example creates a style that changes the ItemsPanel of a ComboBox to a VirtualizingStackPanel.

      <Style TargetType="ComboBox">

        <Setter Property="ItemsPanel">

          <Setter.Value>

            <ItemsPanelTemplate>

              <VirtualizingStackPanel/>

            </ItemsPanelTemplate>

          </Setter.Value>

        </Setter>

      </Style>

Comments