menu

WinUI

  • Code Examples
  • Upgrade Guide
  • User Guide
  • Demos
  • Support
  • Forums
  • Download
Class SfAutoComplete - API Reference

    Show / Hide Table of Contents

    Class SfAutoComplete

    Represent a text control that gives suggestions in a drop down to select item(s). Suggestions are displayed based on entered text along with highlight on best matched item. Allows to select more than one item from suggestion. Suggestions are shown with in-built filters based on text search mode, or allows to show custom filters.

    Inheritance
    System.Object
    DropDownListBase
    SfAutoComplete
    Inherited Members
    DropDownListBase.TextProperty
    DropDownListBase.TextMemberPathProperty
    DropDownListBase.TextBoxStyleProperty
    DropDownListBase.PlaceholderTextProperty
    DropDownListBase.PlaceholderForegroundProperty
    DropDownListBase.HeaderProperty
    DropDownListBase.HeaderTemplateProperty
    DropDownListBase.DescriptionProperty
    DropDownListBase.ItemsSourceProperty
    DropDownListBase.ItemTemplateProperty
    DropDownListBase.ItemTemplateSelectorProperty
    DropDownListBase.DisplayMemberPathProperty
    DropDownListBase.SelectedItemProperty
    DropDownListBase.IsDropDownOpenProperty
    DropDownListBase.MaxDropDownHeightProperty
    DropDownListBase.TokenItemTemplateProperty
    DropDownListBase.TokenItemTemplateSelectorProperty
    DropDownListBase.TokenItemStyleProperty
    DropDownListBase.TokenItemStyleSelectorProperty
    DropDownListBase.SelectedValuePathProperty
    DropDownListBase.SelectedValueProperty
    DropDownListBase.LeadingViewProperty
    DropDownListBase.TrailingViewProperty
    DropDownListBase.HighlightedTextForegroundProperty
    DropDownListBase.HighlightedTextFontWeightProperty
    DropDownListBase.HighlightedTextFontStyleProperty
    DropDownListBase.HighlightedTextFontSizeProperty
    DropDownListBase.OnKeyUp(KeyRoutedEventArgs)
    DropDownListBase.OnPointerEntered(PointerRoutedEventArgs)
    DropDownListBase.OnPointerExited(PointerRoutedEventArgs)
    DropDownListBase.Text
    DropDownListBase.TextMemberPath
    DropDownListBase.TextBoxStyle
    DropDownListBase.PlaceholderText
    DropDownListBase.PlaceholderForeground
    DropDownListBase.Header
    DropDownListBase.HeaderTemplate
    DropDownListBase.Description
    DropDownListBase.ItemsSource
    DropDownListBase.ItemTemplate
    DropDownListBase.ItemTemplateSelector
    DropDownListBase.DisplayMemberPath
    DropDownListBase.SelectedItem
    DropDownListBase.SelectedItems
    DropDownListBase.GroupStyle
    DropDownListBase.IsDropDownOpen
    DropDownListBase.MaxDropDownHeight
    DropDownListBase.TokenItemTemplate
    DropDownListBase.TokenItemTemplateSelector
    DropDownListBase.TokenItemStyle
    DropDownListBase.TokenItemStyleSelector
    DropDownListBase.SelectedValuePath
    DropDownListBase.SelectedValue
    DropDownListBase.LeadingView
    DropDownListBase.TrailingView
    DropDownListBase.HighlightedTextForeground
    DropDownListBase.HighlightedTextFontWeight
    DropDownListBase.HighlightedTextFontStyle
    DropDownListBase.HighlightedTextFontSize
    DropDownListBase.singleSelectionSuggestionTextBlock
    DropDownListBase.multiSelectionSuggestionTextBlock
    Namespace: Syncfusion.UI.Xaml.Editors
    Assembly: Syncfusion.Editors.WinUI.dll
    Syntax
    public class SfAutoComplete : DropDownListBase
    Remarks

    Use an AutoComplete control to select one or more items from the suggestion list. It has several out-of-the-box features such as multiple selection, searching, filtering, UI customization, and custom templates.

    Selection mode

    The AutoComplete control allows you to select a single or multiple items from the suggestion list. The selection mode can be set by using the SelectionMode property. The available selection modes are,

    Single: Select a single item from the suggestion list.

    Multiple: Select multiple items from the suggestion list and display them as tokens, such as in an email address bar. Customizable token representation allows users to remove an item with a close button.

    For more info, regarding selection mode see Selection documentation

    Filtering

    The AutoComplete control comes with a predefined set of filtering modes that filter suggestions based on the characters typed in the text box. The available filtering modes are:

    Start with: Filters the suggestions when the beginning of the string has matches in the list.

    Contains: Filters all the suggestion words that contain the character typed in the text box.

    You can also apply your own custom filter logic to show custom suggestions which gets loaded either asynchronously or synchronously based on your filter criteria using FilterBehavior property.

    Load asynchronous items: GetMatchingItemsAsync method of IAutoCompleteFilterBehavior helps to perform filtering operation on different threads without blocking the current thread by using await Task.Run().

    <editors:SfAutoComplete TextSearchMode="Contains">
           <editors:SfAutoComplete.FilterBehavior>
                   <local:CustomAsyncFilter/>
           </editors:SfAutoComplete.FilterBehavior>
    </editors:SfAutoComplete>
    public class CustomAsyncFilter : IAutoCompleteFilterBehavior
    {
       /// <summary>
       /// Gets the cancellation token source.
       /// </summary>
       CancellationTokenSource cancellationTokenSource;
    

    public async Task<object> GetMatchingItemsAsync(SfAutoComplete source, AutoCompleteFilterInfo filterInfo) { if (this.cancellationTokenSource != null) { this.cancellationTokenSource.Cancel(); this.cancellationTokenSource.Dispose(); }

       this.cancellationTokenSource = new CancellationTokenSource();
       CancellationToken token = this.cancellationTokenSource.Token;
    
      return await Task.Run(() =>
       {
           List&lt;string> list = new List&lt;string>();
           for (int i = 0; i &lt; 100000; i++)
           {
               list.Add(filterInfo.Text + i);
           }
    
           return list;
       }, token);
    

    } }

    For more info, design guidance, and code examples, see Custom filtering documentation

    Searching

    The control highlights the first item that fits the user input in the suggestion list. The AutoComplete control also provides support to apply your own custom search logic to highlight item in the suggestion list based on your search criteria using SearchBehavior property.

    For more info, design guidance, and code examples, see Custom searching documentation

    InputSubmitted

    The InputSubmitted event is triggered, when entered text is submitted that does not correspond to an item in the drop-down list. By using the Item property of AutoCompleteInputSubmittedEventArgs user can add the item to the selected item(s) or set to the selected item that is assigned. If no item is assigned, then in single selection, entered text gets assigned to the selected item. In multiple selection, no text will be added to the selected items.

    <editors:SfAutoComplete ItemsSource="{Binding Sports}"
                            TextMemberPath="Name"
                            DisplayMemberPath="Name"
                            InputSubmitted="OnInputSubmitted">
    </editors:SfAutoComplete>
    private void OnInputSubmitted(object sender, AutoCompleteInputSubmittedEventArgs e)
    {
       e.Item = new Sport() { Name = e.Text};
    }

    UI Customization

    Conditional styling: Customize the appearance of token items conditionally based on the data.

    Token item customization: Token items can be customized with an image or custom control.

    Suggestion box height: The suggestion box height can be adjusted based on the number of items to enhance readability without scrolling.

    Suggestion box item customization: Suggestion box items can be customized with an image or custom control.

    For more info, design guidance, and code examples, see UI Customization

    Examples

    For more info, design guidance, and code examples, see AutoComplete documentation

    Get the demos and source code from below link.

    Syncfusion Controls Gallery app

    View source code of demos in GitHub

    The following example demonstrates, populating items using ItemsSource.

    • XAML
    • C#
    <Grid>
        <Grid.DataContext>
            <local:AutoCompleteViewModel/>
        </Grid.DataContext>
        <editors:SfAutoComplete
            ItemsSource="{Binding Sports}"
            TextMemberPath="Name"
            DisplayMemberPath="Name"/>
    </Grid>
    public class Sport
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }
    
    public class AutoCompleteViewModel
    {
        public ObservableCollection<Sport> Sports { get; set; }
        public AutoCompleteViewModel()
        {
            Sports = new ObservableCollection<Sport>();
            Sports.Add(new Sport() { Name = "Cricket", ID = 0 });
            Sports.Add(new Sport() { Name = "Football", ID = 1 });
            Sports.Add(new Sport() { Name = "Golf", ID = 2 });
            Sports.Add(new Sport() { Name = "Hockey", ID = 3 });
        }
    }

    Constructors

    SfAutoComplete()

    Initializes a new instance of the SfAutoComplete class.

    Declaration
    public SfAutoComplete()

    Fields

    AppendTypeProperty

    Identifies AppendType dependency property.

    Declaration
    public static readonly DependencyProperty AppendTypeProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the AppendType dependency property.

    FilterBehaviorProperty

    Identifies FilterBehavior dependency property.

    Declaration
    public static readonly DependencyProperty FilterBehaviorProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the FilterBehavior dependency property.

    NoResultsFoundContentProperty

    Identifies NoResultsFoundContent dependency property.

    Declaration
    public static readonly DependencyProperty NoResultsFoundContentProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the NoResultsFoundContent dependency property.

    NoResultsFoundTemplateProperty

    Identifies NoResultsFoundTemplate dependency property.

    Declaration
    public static readonly DependencyProperty NoResultsFoundTemplateProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the NoResultsFoundTemplate dependency property.

    SearchBehaviorProperty

    Identifies SearchBehavior dependency property.

    Declaration
    public static readonly DependencyProperty SearchBehaviorProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the SearchBehavior dependency property.

    SelectionModeProperty

    Identifies SelectionMode dependency property.

    Declaration
    public static readonly DependencyProperty SelectionModeProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the SelectionMode dependency property.

    ShowClearButtonProperty

    Identifies ShowClearButton dependency property.

    Declaration
    public static readonly DependencyProperty ShowClearButtonProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the ShowClearButton dependency property.

    TextHighlightModeProperty

    Identifies TextHighlightMode dependency property.

    Declaration
    public static readonly DependencyProperty TextHighlightModeProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the TextHighlightMode dependency property.

    TextSearchModeProperty

    Identifies TextSearchMode dependency property.

    Declaration
    public static readonly DependencyProperty TextSearchModeProperty
    Field Value
    Type Description
    Microsoft.UI.Xaml.DependencyProperty

    The identifier for the TextSearchMode dependency property.

    Properties

    AppendType

    Gets or sets a append type.

    Declaration
    public AutoCompleteAutoAppendType AppendType { get; set; }
    Property Value
    Type Description
    AutoCompleteAutoAppendType

    The default value is AutoCompleteAutoAppendType.TextWithSelection.

    FilterBehavior

    Gets or sets the filter behavior for AutoComplete control by defining the suggestions to be shown in drop down.

    Declaration
    public IAutoCompleteFilterBehavior FilterBehavior { get; set; }
    Property Value
    Type Description
    IAutoCompleteFilterBehavior

    The default value is null.

    Remarks

    Asynchronous filtering not supported for CollectionViewSource.

    Examples

    This example demonstrates how to display the cities in drop-down based on the country name entered in the AutoComplete control.

    • XAML
    • C#
    <editors:SfAutoComplete TextMemberPath = "CityName"
                            DisplayMemberPath="CityName"
                            ItemsSource="{Binding Cities}">
           <editors:SfAutoComplete.FilterBehavior>
               <local:CityFilteringBehavior/>
           </editors:SfAutoComplete.FilterBehavior>
           <editors:SfAutoComplete.DataContext>
              <local:CityViewModel/>
           </editors:SfAutoComplete.DataContext>
    </editors:SfAutoComplete>
    //Model.cs
    public class CityInfo
    {
        public string CityName { get; set; }
        public string CountryName { get; set; }
        public bool IsCapital { get; set; }
    }
    
    //ViewModel.cs
    public class CityViewModel
    {
        public ObservableCollection<CityInfo> Cities { get; set; }
        public CityViewModel()
        {
            this.Cities = new ObservableCollection<CityInfo>();
            this.Cities.Add(new CityInfo() { CityName= "Chicago", CountryName= "USA" });
            this.Cities.Add(new CityInfo() { CityName = "Los Angeles", CountryName = "USA" });
            this.Cities.Add(new CityInfo() { CityName = "Houston", CountryName = "USA" });
            this.Cities.Add(new CityInfo() { CityName = "New York", CountryName = "USA" });
            this.Cities.Add(new CityInfo() { CityName = "Washington", CountryName = "USA", IsCapital = true });
            this.Cities.Add(new CityInfo() { CityName = "Chennai", CountryName = "India" });
            this.Cities.Add(new CityInfo() { CityName = "Delhi", CountryName = "India", IsCapital = true });
            this.Cities.Add(new CityInfo() { CityName = "Kolkata", CountryName = "India" });
            this.Cities.Add(new CityInfo() { CityName = "Mumbai", CountryName = "India" });
            this.Cities.Add(new CityInfo() { CityName = "Berlin", CountryName = "Germany", IsCapital = true });
            this.Cities.Add(new CityInfo() { CityName = "Cologne", CountryName = "Germany" });
            this.Cities.Add(new CityInfo() { CityName = "Hamburg", CountryName = "Germany" });
            this.Cities.Add(new CityInfo() { CityName = "Munich", CountryName = "Germany" });
            this.Cities.Add(new CityInfo() { CityName = "Quebec City", CountryName = "Canada" });
            this.Cities.Add(new CityInfo() { CityName = "Ottawa", CountryName = "Canada", IsCapital = true });
            this.Cities.Add(new CityInfo() { CityName = "Toronto", CountryName = "Canada" });
            this.Cities.Add(new CityInfo() { CityName = "Vancouver", CountryName = "Canada" });
            this.Cities.Add(new CityInfo() { CityName = "Victoria", CountryName = "Canada" });
        }
    }
    
    /// <summary>
    /// Represents a custom filtering behavior for AutoComplete control.
    /// </summary>
    public class CityFilteringBehavior : IAutoCompleteFilterBehavior
    {
       /// <summary>
       /// Returned suggestion list based on the city or country name entered in the AutoComplete control.
       /// </summary>
       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);
       }
    }

    NoResultsFoundContent

    Gets or sets the text displayed when no results are found.

    Declaration
    public object NoResultsFoundContent { get; set; }
    Property Value
    Type Description
    System.Object

    The text to display when no results are found. The default is value is ‘No Results Found’.

    Examples

    The following example shows how to define a NoResultsFoundContent for the control.

    <editor:SfAutoComplete 
                TextMemberPath ="CityName"
                DisplayMemberPath="CityName"
                ItemsSource="{Binding Cities}"
                NoResultsFoundContent="Not Found" />

    NoResultsFoundTemplate

    Gets or sets the DataTemplate used to display in the dropdown when no results are found in the search.

    Declaration
    public DataTemplate NoResultsFoundTemplate { get; set; }
    Property Value
    Type Description
    Microsoft.UI.Xaml.DataTemplate

    The template that specifies the visualization of the dropdown when no results are found in the search. The default value is null.

    Remarks

    The NoResultsFoundContent value is the data context of this DataTemplate.

    Examples

    The following example shows how to define a NoResultsFoundTemplate for the control.

    <editors:SfAutoComplete 
                  TextMemberPath ="CityName" 
                  DisplayMemberPath="CityName"
                  ItemsSource="{Binding Cities}"
                  NoResultsFoundContent="Not Found">
       <editors:SfAutoComplete.NoResultsFoundTemplate>
            <DataTemplate>
                <TextBlock 
                   Text ="{Binding}"
                   Foreground="Red"
                   FontStyle="Italic"
                   FontSize="20" />
            </DataTemplate> 
       </editors:SfAutoComplete.NoResultsFoundTemplate>
    </editors:SfAutoComplete>

    SearchBehavior

    Gets or sets the search behavior for AutoComplete control which defines the highlighted index based on filterted items.

    Declaration
    public IAutoCompleteSearchBehavior SearchBehavior { get; set; }
    Property Value
    Type Description
    IAutoCompleteSearchBehavior

    The default value is null.

    Examples

    This example demonstrates how to display the cities in drop-down based on the country name entered in the AutoComplete control.

    • XAML
    • C#
    <editors:SfAutoComplete TextMemberPath = "CityName"
                            DisplayMemberPath="CityName"
                            ItemsSource="{Binding Cities}">
           <editors:SfAutoComplete.FilterBehavior>
               <local:CityFilteringBehavior/>
           </editors:SfAutoComplete.FilterBehavior>
           <editors:SfAutoComplete.SearchBehavior>
               <local:CapitalCitySearchingBehavior/>
           </editors:SfAutoComplete.SearchBehavior>
    </editors:SfAutoComplete>
    /// <summary>
    /// Represents a custom searching behavior for AutoComplete control.
    /// </summary>
    public class CapitalCitySearchingBehavior : IAutoCompleteSearchBehavior
    {
       public int GetHighlightIndex(SfAutoComplete source, AutoCompleteSearchInfo searchInfo)
       {
           var filteredCapitals = from CityInfo cityInfo in searchInfo.FilteredItems
                                  where cityInfo.IsCapital
                                  select searchInfo.FilteredItems.IndexOf(cityInfo);
    
           if (filteredCapitals.Count() > 0)
                return filteredCapitals.FirstOrDefault();
    
           return 0;
       }
    }

    SelectionMode

    Gets or sets the selection behavior for the SfAutoComplete control.

    Declaration
    public AutoCompleteSelectionMode SelectionMode { get; set; }
    Property Value
    Type Description
    AutoCompleteSelectionMode

    A value that indicates the selection behavior for a AutoComplete control. The default value is Single. Fields:

    EnumerationDescription
    SingleAllows to select a single item from a list.
    MultipleAllows to select one or more items from a list.
    Remarks

    Allows to select either a single item or multiple items.

    ShowClearButton

    Gets or sets a value indicating whether to show the clear button in the editable text box.

    Declaration
    public bool ShowClearButton { get; set; }
    Property Value
    Type Description
    System.Boolean

    The default value is true.

    Remarks

    Click clear button to clear the text in the editable text box. The Clear button shown only in editable mode.

    TextHighlightMode

    Gets or sets a text highlighting mode.

    Declaration
    public AutoCompleteTextHighlightMode TextHighlightMode { get; set; }
    Property Value
    Type Description
    AutoCompleteTextHighlightMode

    The default value is AutoCompleteTextHighlightMode.None.

    TextSearchMode

    Gets or sets the TextSearchMode to search the item which matches the search text either with the beginning of the texts or contains the search text in the list.

    Declaration
    public AutoCompleteTextSearchMode TextSearchMode { get; set; }
    Property Value
    Type Description
    AutoCompleteTextSearchMode

    A value that indicates the text search behavior for a AutoComplete control. The default value is StartsWith. Fields:

    EnumerationDescription
    StartsWithSearch the item which matches the search text with the beginning of the texts in the list.
    ContainsSearch the item which contains the search text in the list.

    Methods

    Dispose()

    Dispose the Control from the memory.

    Declaration
    public override void Dispose()
    Overrides
    DropDownListBase.Dispose()

    OnApplyTemplate()

    Declaration
    protected override void OnApplyTemplate()
    Overrides
    DropDownListBase.OnApplyTemplate()

    OnCreateAutomationPeer()

    Declaration
    protected override AutomationPeer OnCreateAutomationPeer()
    Returns
    Type Description
    Microsoft.UI.Xaml.Automation.Peers.AutomationPeer

    OnGotFocus(RoutedEventArgs)

    Declaration
    protected override void OnGotFocus(RoutedEventArgs e)
    Parameters
    Type Name Description
    Microsoft.UI.Xaml.RoutedEventArgs e
    Overrides
    DropDownListBase.OnGotFocus(RoutedEventArgs)

    OnLostFocus(RoutedEventArgs)

    Declaration
    protected override void OnLostFocus(RoutedEventArgs e)
    Parameters
    Type Name Description
    Microsoft.UI.Xaml.RoutedEventArgs e
    Overrides
    DropDownListBase.OnLostFocus(RoutedEventArgs)

    OnPointerReleased(PointerRoutedEventArgs)

    Declaration
    protected override void OnPointerReleased(PointerRoutedEventArgs e)
    Parameters
    Type Name Description
    Microsoft.UI.Xaml.Input.PointerRoutedEventArgs e

    OnPreviewKeyDown(KeyRoutedEventArgs)

    Declaration
    protected override void OnPreviewKeyDown(KeyRoutedEventArgs e)
    Parameters
    Type Name Description
    Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e

    Events

    InputSubmitted

    Occurs when the user submits some text that does not correspond to an item in the AutoComplete dropdown list.

    Declaration
    public event EventHandler<AutoCompleteInputSubmittedEventArgs> InputSubmitted
    Event Type
    Type Description
    System.EventHandler<AutoCompleteInputSubmittedEventArgs>
    Examples

    This example demonstrates how to invoke InputSubmitted event.

    • XAML
    • C#
        <editors:SfAutoComplete
            x:Name="autoComplete"
            ItemsSource="{Binding Countries}"
            TextMemberPath="Name"
            DisplayMemberPath="Name"
            InputSubmitted="OnInputSubmitted" />
    private async void OnInputSubmitted(object sender, AutoCompleteInputSubmittedEventArgs e)
    {
       var cd = new ContentDialog
       {
         Content = "Enter a country from the list.",
         CloseButtonText = "Close"
       };
    
       cd.XamlRoot = this.Content.XamlRoot;
       var result = await cd.ShowAsync();
    }

    SelectionChanged

    Occurs when the SelectedItem or SelectedItems is changed.

    Declaration
    public event EventHandler<AutoCompleteSelectionChangedEventArgs> SelectionChanged
    Event Type
    Type Description
    System.EventHandler<AutoCompleteSelectionChangedEventArgs>
    Examples

    This example demonstrates how to invoke SelectionChanged event.

    • XAML
    • C#
        <editors:SfAutoComplete
            x:Name="autoComplete"
            ItemsSource="{Binding Countries}"
            TextMemberPath="Name"
            DisplayMemberPath="Name"
            SelectionChanged="OnAutoCompleteSelectionChanged" />
    private async void OnAutoCompleteSelectionChanged(object sender, AutoCompleteSelectionChangedEventArgs e)
    {
       var cd = new ContentDialog
       {
         Content = "Selected item was changed.",
         CloseButtonText = "Close"
       };
    
       cd.XamlRoot = this.Content.XamlRoot;
       var result = await cd.ShowAsync();
    }
    Back to top Generated by DocFX
    Copyright © 2001 - 2023 Syncfusion Inc. All Rights Reserved