WPF: How to improve performance of AutoCompleteBox with a simple trick

By default the AutoCompleteBox doesn’t use UI virtualization, so when you have lots of items, performance can suffer and your application can even freeze.

To understand the following fix, we need to know the template used by the AutoCompleteBox.

The AutoCompleteBox uses a ListBox to display its results. The ListBox supports virtualization, but because there is no MaxHeight set, UI elements for all items will be created, even those that are not shown.

With this simple style we force a MaxHeight to the internal ListBox and make sure virtualization is being used:

<Style x:Key="AutoCompleteBoxStyle" TargetType="{x:Type toolkit:AutoCompleteBox}">
    <Style.Resources>
        <Style TargetType="{x:Type ListBox}">
            <Setter Property="MaxHeight" Value="200" />
        </Style>
    </Style.Resources>
</Style>

And you use it like any other style:

<toolkit:AutoCompleteBox
    Style="{StaticResource AutoCompleteBoxStyle}"
    ItemsSource="{Binding ItemCollection}" />

As you can see, we make an internal style inside the AutoCompleteBox style and target the LisBox by type. Because the default template only has one ListBox, this suits us well and we don’t have to redefine the whole template.

There are other alternatives you can use to improve the performance of the AutoCompleteBox:

  • Override the actual AutoCompleteBox template and set MaxHeight directly in the ListBox control (similar result as the above).
  • Change MinimumPrefixLength property to a bigger value. Results will only be shown after typing a certain number of characters.
  • Run the autocomplete search in the background by implementing the Populating event.
  • Limit the total results shown by implementing your own AutoCompleteFilterPredicate and using the ItemFilter property.
Nuno Freitas
Posted by Nuno Freitas on April 23, 2014

Related articles