Introduction
SearchBar view control is the control that provides you the way to search from the list of contents.
It has the events 'SearchButtonPressed', 'TextChanged' for performing actions respectively.
You can give the list of items that are required to perform the search for the item based on conditions and suggestions you want.
This article will cover the following,
- SearchBar view.
- SearchBar events.
- ListView for generating the values and selection of values
Prerequisite
- Knowledge in c#.
- Basics of Xamarin.
Implementation
Open Visual studio and select new project,
Select project type and give project name,
Select template – Blank App and code sharing as PCL.
Set the target and platform version as below,
Set the below configurations,
Open MainPage.xaml from Portable project and modify the contents as below,
- <?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:local="clr-namespace:SearchDemo"
- x:Class="SearchDemo.MainPage" BackgroundColor="Cyan">
- <StackLayout Orientation="Vertical">
- <Label Text="Search Country" FontSize="30"></Label>
- <SearchBar x:Name="SearchContent" TextChanged="SearchContent_TextChanged"></SearchBar>
- <Grid>
- <ListView x:Name="CountryList" ItemTapped="CountryList_ItemTapped"></ListView>
- </Grid>
- </StackLayout>
- </ContentPage>
Open MainPage.xaml.cs and modify the contents as below,
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Xamarin.Forms;
-
- namespace SearchDemo
- {
- public partial class MainPage : ContentPage
- {
- List<string> country = new List<string>
- {
- "India",
- "pakistan",
- "Srilanka",
- "Bangladesh",
- "Afghanistan"
- };
- public MainPage()
- {
- InitializeComponent();
- }
-
- private void SearchContent_TextChanged(object sender, TextChangedEventArgs e)
- {
- var keyword = SearchContent.Text;
- if (keyword.Length >= 1)
- {
- var suggestion = country.Where(c => c.ToLower().Contains(keyword.ToLower()));
- CountryList.ItemsSource = suggestion;
- CountryList.IsVisible = true;
- }
- else
- {
- CountryList.IsVisible = false;
- }
- }
-
- private void CountryList_ItemTapped(object sender, ItemTappedEventArgs e)
- {
- if (e.Item as string == null)
- {
- return;
- }
- else
- {
- CountryList.ItemsSource = country.Where(c=> c.Equals(e.Item as string));
- CountryList.IsVisible = true;
- SearchContent.Text = e.Item as string;
- }
-
- }
- }
- }
Note
Create the new Project as I have attached only Portable project in this article.
Run the application,
Enter any keyword for getting the available suggestion.
Selecting any item will fill its containing value.
You can perform the suggestion on searchbutton click event ' SearchButtonPressed'.
See the same output in Android emulator.