Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created February 10, 2012 10:12
Show Gist options
  • Select an option

  • Save follesoe/1788452 to your computer and use it in GitHub Desktop.

Select an option

Save follesoe/1788452 to your computer and use it in GitHub Desktop.
Showing how to do as-you-type search in WP7
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;
using Posten.Pakkesporing.Lib.Model;
using Posten.Pakkesporing.Lib.Services;
namespace Posten.Pakkesporing.Lib.ViewModels
{
public class PostUnitsViewModel : BaseViewModel
{
public ObservableCollection<PostUnitAnnotation> PostUnits { get; private set; }
public List<PostUnitAnnotation> AllPostUnits { get; private set; }
private readonly PostUnitsService _unitsService;
private readonly Timer _timer;
private string _searchTerm;
private bool _isSearching;
public PostUnitsViewModel()
{
_unitsService = new PostUnitsService();
PostUnits = new ObservableCollection<PostUnitAnnotation>();
AllPostUnits = new List<PostUnitAnnotation>();
_timer = new Timer(ExecuteSearch, null, int.MaxValue, int.MaxValue);
}
public void Search(string term)
{
_searchTerm = term.ToLower();
if(string.IsNullOrEmpty(_searchTerm))
{
_timer.Change(int.MaxValue, int.MaxValue);
SearchByLocation();
}
else
{
_timer.Change(300, int.MaxValue);
}
}
private void ExecuteSearch(object state)
{
if (_isSearching) _timer.Change(300, int.MaxValue);
ThreadPool.QueueUserWorkItem(o => {
_searchEvent.WaitOne();
_searchEvent.Reset();
_isSearching = true;
LoadUnitsIfEmpty();
Deployment.Current.Dispatcher.BeginInvoke(() => PostUnits.Clear());
foreach (var unit in AllPostUnits)
{
if (unit.Name.ToLower().Contains(_searchTerm) ||
unit.Address.ToLower().Contains(_searchTerm))
{
unit.DisplayDistance = false;
PostUnitAnnotation dispatchUnit = unit;
Deployment.Current.Dispatcher.BeginInvoke(() => PostUnits.Add(dispatchUnit));
}
}
_isSearching = false;
_searchEvent.Set();
});
}
public void LoadUnitsIfEmpty()
{
lock (AllPostUnits)
{
if (AllPostUnits.Count == 0)
{
AllPostUnits.AddRange(_unitsService.GetAnnotationsForAllUnits());
}
}
}
private readonly ManualResetEvent _searchEvent = new ManualResetEvent(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment