Autocomplete Entry With Suggestion Dropdown In Xamairn.Forms

By Harshad Patel Last Updated 1245 Days Ago 7 Minutes Read App Development 0
Smart Entrepreneurs

AutoCompleteBox is an editable entry element that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.

Overview

To create a text entry widget that provides auto-complete suggestions, create AutoCompleteBox controls for xamarin forms. Suggestions are received from a collection of strings associated with the controls through an Array of strings.

To set up a solution, we will start by creating a blank application. We will use the Blank Forms App (Multiplatform) provided by Xamarin. This template shares code using a .NET Standard Shared project. Start a new project named XFAutoCompletes.

AutocompleteEntry (3)

Must check: Top 8 Reasons Xamarin App Development Could Help You to Grow Your Business

AutocompleteEntry (2)

Visual Studio will create the basic structure of the solution for us, including the platform-specific project & one shared project

Step 1 :

Create a controls name as AutoCompleteBox.xaml,

AutocompleteEntry (1)

We will start with a basic layout of the control. So we will open the AutoCompleteBox.xaml file and replace the default content by a grid containing two row with entry and listview in the first row and a listview ch in the second row. We also bind the ItemSource and the others properties to upcoming BindableProperties of our control.

We also set the x:Name property of the class to this.

<?xml version=”1.0″ encoding=”UTF-8″?>
<Grid
xmlns=”http://xamarin.com/schemas/2014/forms”
xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”
xmlns:controls=”clr-namespace:XFAutoCompleteBox.Controls”
x:Class=”XFAutoCompleteBox.Controls.AutoCompleteBox”
x:Name=”this”>
<Grid.RowDefinitions>
<RowDefinition Height=”50″/>
<RowDefinition Height=”Auto”/>
</Grid.RowDefinitions>
<Frame
Grid.Row=”0″
HasShadow=”False”
BorderColor=”LightGray”
CornerRadius=”10″
HorizontalOptions=”FillAndExpand”
VerticalOptions=”FillAndExpand”
Margin=”0″
Padding=”8″>
<controls:CommanEntry
x:Name=”entry”
BackgroundColor=”White”
PlaceholderColor=”{Binding PlaceholderColor, Source={x:Reference this}}”
Placeholder=”{Binding Placeholder, Source={x:Reference this}}”
TextColor=”{Binding TextColor, Source={x:Reference this}}”
FontSize=”{Binding FontSize, Source={x:Reference this}}”
ReturnType=”{Binding ReturnType, Source={x:Reference this}}”
Keyboard=”{Binding Keyboard, Source={x:Reference this}}”
IsBorder=”False”
HorizontalOptions=”FillAndExpand”
VerticalOptions=”FillAndExpand”
TextChanged=”Entry_TextChanged”>
</controls:CommanEntry>
</Frame>
<ListView
Grid.Row=”1″
x:Name=”listView”
SeparatorVisibility=”None”
HasUnevenRows=”False”
RowHeight=”45″
IsVisible=”False”
ItemSelected=”listView_ItemSelected”>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout
Orientation=”Vertical”
VerticalOptions=”FillAndExpand”
HorizontalOptions=”FillAndExpand”>
<Label
Text = “{Binding .}”
FontSize=”18″
HorizontalOptions=”FillAndExpand”
VerticalOptions=”FillAndExpand”
HorizontalTextAlignment=”Start”
TextColor=”Gray”
Padding=”5,0″
VerticalTextAlignment=”Center”/>
<BoxView
BackgroundColor=”LightGray”
HeightRequest=”1″/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>

Step 2:

Let’s create the currently missing BindableProperties in the code-behind file of our AutoCompleteBox.cs class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Xamarin.Forms;

namespace XFAutoCompleteBox.Controls
{
public partial class AutoCompleteBox : Grid
{
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(
nameof(ItemsSource),
typeof(IEnumerable<object>),
typeof(AutoCompleteBox));

public IEnumerable<object> ItemsSource
{
get { return (IEnumerable<object>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}

public static readonly BindableProperty TextProperty =
BindableProperty.Create(nameof(Text), typeof(string), typeof(AutoCompleteBox), string.Empty);//, BindingMode.TwoWay, null, HandleBindingPropertyChangedDelegate);

public static readonly BindableProperty PlaceholderProperty =
BindableProperty.Create(nameof(Placeholder), typeof(string), typeof(AutoCompleteBox), string.Empty);

public static readonly BindableProperty TextColorProperty =
BindableProperty.Create(nameof(TextColor), typeof(Color), typeof(AutoCompleteBox), Color.Black);

public static readonly BindableProperty PlaceholderColorProperty =
BindableProperty.Create(nameof(PlaceholderColor), typeof(Color), typeof(AutoCompleteBox), Color.Black);

public static readonly BindableProperty FontSizeProperty =
BindableProperty.Create(nameof(FontSize), typeof(double), typeof(AutoCompleteBox), 17d);

public static readonly BindableProperty ReturnTypeProperty =
BindableProperty.Create(nameof(ReturnType), typeof(ReturnType), typeof(AutoCompleteBox), ReturnType.Default);

public static readonly BindableProperty KeyboardProperty =
BindableProperty.Create(nameof(Keyboard), typeof(Keyboard), typeof(AutoCompleteBox), Keyboard.Default, coerceValue: (o, v) => (Keyboard)v ?? Keyboard.Default);

public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}

public string Placeholder
{
get { return (string)GetValue(PlaceholderProperty); }
set { SetValue(PlaceholderProperty, value); }
}

public Color TextColor
{
get { return (Color)GetValue(TextColorProperty); }
set { SetValue(TextColorProperty, value); }
}

public Color PlaceholderColor
{
get { return (Color)GetValue(PlaceholderColorProperty); }
set { SetValue(PlaceholderColorProperty, value); }
}

public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}

public ReturnType ReturnType
{
get { return (ReturnType)GetValue(ReturnTypeProperty); }
set { SetValue(ReturnTypeProperty, value); }
}

public Keyboard Keyboard
{
get { return (Keyboard)GetValue(KeyboardProperty); }
set { SetValue(KeyboardProperty, value); }
}

public AutoCompleteBox()
{
InitializeComponent();
}

protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName.Equals(ItemsSourceProperty.PropertyName))
{
ItemsSource = ItemsSource;
}
}

void Entry_TextChanged(System.Object sender, Xamarin.Forms.TextChangedEventArgs e)
{
if (e.NewTextValue.Length > 0)
{
listView.IsVisible = true;
var filterItem = ItemsSource.Where(x => (x as string).ToLower().Contains(e.NewTextValue.ToLower())).ToList();
listView.ItemsSource = filterItem;
if(filterItem != null)
{
listView.HeightRequest = filterItem.Count * 45 > 200 ? 200 : filterItem.Count * 45;
}
}
else
{
listView.IsVisible = false;
}
}

void listView_ItemSelected(System.Object sender, Xamarin.Forms.SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null) return;
if (sender is ListView lv) lv.SelectedItem = null;

var tt = e.SelectedItem as string;
entry.Text = tt;
listView.IsVisible = false;
}
}
}

Step 3:

Create an XML file named MainPage.xml and save it inside the Pages folder. Edit the file to look like this:

This file defines a simple AutoCompleteBox that will be used for each item that appears in the list of suggestions.

<?xml version=”1.0″ encoding=”utf-8″?>
<ContentPage
xmlns=”http://xamarin.com/schemas/2014/forms”
xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”
xmlns:d=”http://xamarin.com/schemas/2014/forms/design”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
mc:Ignorable=”d”
xmlns:controls=”clr-namespace:XFAutoCompleteBox.Controls”
x:Class=”XFAutoCompleteBox.Pages.MainPage”
BackgroundColor=”#f2f2f2″>
<StackLayout>
<controls:AutoCompleteBox
Margin=”20,50″
HorizontalOptions=”FillAndExpand”
VerticalOptions=”FillAndExpand”
Placeholder=”Email here!”
PlaceholderColor=”LightGray”
TextColor=”Black”
Keyboard=”Default”
Text=”{Binding SuggestionText}”
ItemsSource=”{Binding SuggestionItem}”>
</controls:AutoCompleteBox>
</StackLayout>
</ContentPage>

Step 4:

And write some code in MainPage.cs class

using Xamarin.Forms;
using XFAutoCompleteBox.ViewModels;

namespace XFAutoCompleteBox.Pages
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainViewModel();
}
}
}

Step 5:

And the write some code in MainViewModel.cs class,

Initial declared ObservableCollection,

ObservableCollection<string> _suggestionItem;
public ObservableCollection<string> SuggestionItem
{
get => _suggestionItem;
set
{
_suggestionItem = value;
OnPropertyChanged();
}
}

Then add values in ObservableCollection through method and now call this method BindData() in Constructor,

public MainViewModel()
{
BindData();
}

public void BindData()
{
var strSuggestionArr = new string[] {
“harshad@mobmaxime.com”,
“sagar.p@mobmaxime.com”,
“kapil@mobmaxime.com”,
“harry@test.com”,
“xamarin@test.com”,
“xamarinteam@mob.com”
};

SuggestionItem = new ObservableCollection<string>(strSuggestionArr.ToList());
}

Here is the full code of MainViewModel.cs,

using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace XFAutoCompleteBox.ViewModels
{
public class MainViewModel : BaseViewModel
{
public MainViewModel()
{
BindData();
}

public void BindData()
{
var strSuggestionArr = new string[] {
“harshad@mobmaxime.com”,
“sagar.p@mobmaxime.com”,
“kapil@mobmaxime.com”,
“harry@test.com”,
“xamarin@test.com”,
“xamarinteam@mob.com”
};
SuggestionItem = new ObservableCollection<string>(strSuggestionArr.ToList());
}
ObservableCollection<string> _suggestionItem;
public ObservableCollection<string> SuggestionItem
{
get => _suggestionItem;
set
{
_suggestionItem = value;
OnPropertyChanged();
}
}
string _suggestionText;
public string SuggestionText
{
get => _suggestionText;
set
{
_suggestionText = value;
OnPropertyChanged();
}
}
}
}

Step 6:

Here is the final result iOS and Android:

Source-Code:

You can find the whole source-code in my Download.

Happy Coding!

Looking for Hire Nearshore App Developers?

We have a dedicated team of experienced certified professionals who have the objective of serving customers with better expectations and experience.

Read More
Social Media :

Join 10,000 subscribers!

Join Our subscriber’s list and trends, especially on mobile apps development.

I hereby agree to receive newsletters from Mobmaxime and acknowledge company's Privacy Policy.