Search through ListView items in Xamarin Forms


So basically there are 2 things we need to have

  1. a list view with items in it.
  2. a search bar to input search query on.

and that would be very much of it.
in the XAML part, I will just include these 2 things but of course, you can be creative and manipulate the view.

<ContentPage.Content>
<Grid x:Name="_rootGrid">
//SearchBar
<SearchBar IsVisible="{Binding SearchMode}" Placeholder="Search items.." Text="{Binding SearchText}">
<SearchBar.Behaviors>
<behaviors:EventToCommandBehavior EventName="TextChanged" Command="{Binding SearchCommand}"/>
</SearchBar.Behaviors>
</SearchBar>
//ListView
<ListView x:Name="_ListView" ItemsSource="{Binding Items}"
ItemTemplate="{StaticResource ItemListDataSourceSelector}" HasUnevenRows="True"/>
</Grid>
</ContentPage.Content>

I’m more of an MVVM person and prefer keeping the Code behind clean in the xaml.cs, but you can do it either way, in the ViewModel or Code Behind. this should not matter.

#region Fields
private ObservableCollection<object> _Items;
private ObservableCollection<object> _ItemsFiltered;
private ObservableCollection<object> _ItemsUnfiltered;
private string _searchText;
#endregion
#region Properties
public string SearchText
{
get { return _searchText; }
set
{
_searchText = value;
OnPropertyChanged("SearchText");
}
}
public ObservableCollection<object> Items
{
get { return _Items; }
set
{
_Items = value;
OnPropertyChanged("Items");
}
}
#endregion
#region Commands
public ICommand SearchCommand { get; private set; }
#endregion
#region Constructor
public ItemsViewModel()
{
Items = new ObservableCollection<object>();
GetItems();
SearchCommand = new Command(PerformSearch);
}
#endregion
#region Methods
public void PerformSearch()
{
if (string.IsNullOrWhiteSpace(this._searchText))
Items = _ItemsUnfiltered;
else
{
_ItemsFiltered = new ObservableCollection<object>(_ItemsUnfiltered.Where(i =>
(i is ItemObj && (((ItemObj)i).ItemObjName.ToLower().Contains(_searchText.ToLower())));
Items = _ItemsFiltered;
}
}
#endregion

Android preview. Works on iOS and UWP as well.

In the GetItems method make sure you assign _ItemsUnfiltered = _Items This makes sure the original contents are not operated on and on clearing the text input of search we can get back the original list. 😉
Also, make sure your ViewModel has an inheritance of INotifyPropertyChanged so as to hit the OnPropertyChanged(nameof(SomeCommandOrBinding))

That would be very much of the searching thing, you can add as many filter criteria as you want in the lambda expression above. just keep ORing ( A || B ) or ANDing ( A && B ) them. (i prefer ORing).

p.s. I’ve used an EventToCommandBehavior to bind a command to an event of text changed, you can easily find a code for that. If you don’t? feel free to drop by 🙂

update: Check Binding Event To Command.

You can download the code from here and also make contibutions.

Pingback for assistance, your Feedback’s are always a welcome… 🙂

Regards,
Aditya Deshpande

7 thoughts on “Search through ListView items in Xamarin Forms

  1. Hi Aditya,

    Great article, thanks for writing it. Do you have a working example that we can download? Thanks again!

    Regards,

    Filip

    Like

  2. The problem my list is binded to a firebase Database.. So the list is not hard coded.. And I’m getting some errors how can I fix that..

    Error : Cannot Convert system. Threading Task to System.Collections. Generics

    Like

    1. instead of returning Task Try returning Task<List> and use the Result to bind to observableCollection.
      for the demo purpose, I have used Hardcoded list in every scenario an API or DAL will be providing the items.
      if you are unable to get through this feel free to reach me on email or twitter. 🙂

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s