Skip to content

Instantly share code, notes, and snippets.

@RedTahr
Created June 18, 2015 22:06
Show Gist options
  • Save RedTahr/e10381af8912221a3e6f to your computer and use it in GitHub Desktop.
Save RedTahr/e10381af8912221a3e6f to your computer and use it in GitHub Desktop.
Xamarin.Forms (as of 1.4.2.6359) SearchBar with filter and grouping
// should be able to bind to this in XAML, but haven't found success doing this yet
search.TextChanged += (sender, args) => { ViewModel.Filter(args.NewTextValue); };
using System.Collections.Generic;
using System.Collections.ObjectModel;
// from Xamarin Monkey demo - http://motzcod.es/post/93792500152/custom-listview-viewcells-in-xamarin-forms
namespace Interact.Core.Helper {
public class Grouping<TKey, TValue> : ObservableCollection<TValue> {
public TKey Key { get; private set; }
public Grouping(TKey key, IEnumerable<TValue> items) {
Key = key;
foreach (var item in items)
this.Items.Add(item);
}
}
}
public void Filter(string filter) {
filteredPeople.Clear();
if (string.IsNullOrEmpty(filter)) {
GroupCollections(list);
}
else {
foreach (var person in people) {
if (person.FullName.ToLower().Contains(filter.ToLower())) {
filteredPeople.Add(person);
}
}
GroupCollections(filteredPeople);
}
}
// the general idea, edited in-situ to make it a bit generic
private void GroupCollections(ObservableCollection<Detail> ToBeGrouped) {
peopleGrouped.Clear();
var sorted = from people in ToBeGrouped
orderby people.NameSort
group people by people.NameSort into peopleGroup
select new Grouping<string, Detail>(peopleGroup.Key, peopleGroup);
peopleGrouped = new ObservableCollection<Grouping<string, Detail>>(sorted);
}
<SearchBar x:Name="search" Placeholder="Search" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment