Articles in this section

How to Add Custom Filtering in WinUI AutoComplete Control

This article explains how to add custom filtering in the WinUI AutoComplete control.

The AutoComplete control provides support to apply your own custom filter logic to suggest items based on your filter criteria by using the FilterBehavior and SearchBehavior properties. The default value of FilterBehavior and SearchBehavior is null.

Now, let us create a custom filtering class to apply your filter logic to AutoComplete control by following these steps:

Step 1: Create a class that derives from the IAutoCompleteFilterBehavior interface.

C#
/// <summary>
/// Represents a custom filtering behavior for `AutoComplete` control. 
/// </summary>
public class CityFilteringBehavior : IAutoCompleteFilterBehavior
{

}

Step 2: Then, implement the GetMatchingIndexes method of the IAutoCompleteFilterBehavior interface to create your own suggestion list (containing the indices of the filtered items) based on the text entered in the AutoComplete control that needs to be shown in the drop-down. The GetMatchingIndexes method contains the following arguments:

  • source - The owner of the filter behavior, which holds information about the ItemsSource, Items properties, and so on.
  • filterInfo - Contains details about the text entered in the AutoComplete control. Using this text, you can prepare suggestion list, which gets displayed in the drop-down list.
C#
public class CustomFilter : IAutoCompleteFilterBehavior
{
   public async Task<object> GetMatchingItemsAsync(SfAutoComplete source, AutoCompleteFilterInfo filterInfo)
   {
        IEnumerable itemssource = source.ItemsSource as IEnumerable;
        var filteredItems = (from CityInfo item in itemssource
                                where item.CountryName.StartsWith(filterInfo.Text, StringComparison.CurrentCultureIgnoreCase) ||
                                      item.CityName.StartsWith(filterInfo.Text, StringComparison.CurrentCultureIgnoreCase)
                                select item);
        return await Task.FromResult(filteredItems);  
   }
}

Step 3: Applying custom filtering to the AutoComplete control by using the FilterBehavior property.

XAML
<editors:sfautocomplete textmemberpath="CityName" displaymemberpath="CityName" itemssource="{Binding Cities}">
   <editors:sfautocomplete.filterbehavior>
       <local:cityfilteringbehavior>
   </local:cityfilteringbehavior></editors:sfautocomplete.filterbehavior>
</editors:sfautocomplete>

The following GIF shows how to display cities in a drop-down based on the country name entered in the AutoComplete control.

winui-autocomplete-custom-filtering-searching.gif

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied