Using Xamarin.Forms to create a sortable list view

Seems like Xamarin.Forms has captured my imagination lately, and given me reason to write more. When building FootballTournament2014 I noticed that Xamarin.Forms did not have a built-in searchable list view, so I thought I would see if I could build it myself. I am certain there is a way to build this using reactive programming, but I didn't start out that way and didn't mind how the form turned out.

Like all things Xamarin.Forms, it is surprisingly easy to build.

  • In the ViewModel, add a placeholder list, which will serve as the ViewModels filtered list. The observable collection will be used by the View.

    private List<Team> keepTeams = new List<Team>();
    private List<Team> keepTeams = new List<Team>();
    public ObservableCollection<Team> Teams
        get { return _teams; }
        set { _teams = value; OnPropertyChanged("Teams"); }

    When we get the teams back from the service, set the list equal to the response.

    keepTeams = Teams.ToList();
  • Add a sort method to the ViewModel, this will be hooked in later.

    public void FilterTeams(string text)
        keepTeams.Where(t => t.Name.ToLower().Contains(text.ToLower())).ToList().ForEach(t => Teams.Add(t));

    This method filters the list of teams and updates the observable collection based on the result. This uses a semi-fuzzy search to scan for Contains instead of StartsWith.

  • In the View, create a search bar control and add it to the content of the View.

    var searchBar = new SearchBar();
        searchBar.TextChanged +=  (sender, e) => {

    Note the subscription to TextChanged, which calls our ViewModel method created earlier.

    Make sure to add the list view as well, here is an abreviated snippet.

    var listView = new ListView();
    listView.ItemsSource = ViewModel.Teams;
    stack.Children.Add (listView);

That's it

image of three platforms running searchable list view

You now have a searchable list view built with Xamarin.Forms that still has 100% code sharing, UI included.

As always, you can view the code here for reference.

comments powered by Disqus