在Silverlight中实现“在键入时搜索”

时间:2011-01-19 18:03:45

标签: silverlight silverlight-4.0

我正在尝试在Silverlight应用程序中键入 屏幕时实施 搜索。我的想法是我有一个带有textedit控件和列表框的屏幕。列表框中包含了我的所有数据。

当用户在文本框中键入内容时,会发生以下情况:

  • 隐藏了不包含用户输入中所有字母的所有项目。
  • 可见列表项的匹配字母以不同颜色突出显示。

我不知道如何从这开始,所以欢迎所有指针,样品和提示!

2 个答案:

答案 0 :(得分:7)

我建议使用CollectionViewSource。 CollectionViewSource具有过滤项目的功能。您可以将ListBox绑定到CollectionViewSource并处理Filter事件以进行过滤。将“搜索框”绑定到Text属性,您可以在Filter事件中使用该属性。您可以通过调用CollectionViewSource View上的Refresh方法来处理TextBox控件的“KeyUp”事件以启动过滤。

使用CollectionViewSource过滤数据:http://xamlcoder.com/blog/2010/10/27/filtering-data-using-collectionviewsource/

http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.filter.aspx

http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview.aspx

http://timheuer.com/blog/archive/2009/11/04/updated-silverlight-3-datagrid-grouping-data-pagedcollectionview.aspx

http://bea.stollnitz.com/blog/?p=392

Sudo代码:

// ViewModel - properties should fire NotifyPropertyChanged
public class ViewModel : INotifyPropertyChanged
{
  public ViewModel
  {
    this.Data = new CollectionViewSource();
    this.Data.Source = this.GenerateObjects();
    this.Data.Filter += (s,e) =>
    {
      // TODO: add filter logic
      DataObject item = e.Item as DataObject;
      return item.Name.Contains(this.SearchText);
    };
  }
  public string SearchText{get;set;}
  public CollectionViewSource Data {get;set;}

  private List<DataObject> GenerateObjects(){ // generate list of data objects }
}

// View XAML
<StackPanel>
  <TextBox Text="{Binding SearchText, Mode=TwoWay}" KeyUp="OnKeyUp"/>

  <ListBox ItemsSource="{Binding Data.View}"/>
</StackPanel>


// View Code Behind
public class View : UserControl
{
  public View() { this.DataContext = new ViewModel(); }

  private ViewModel ViewModel { get { return this.DataContext as ViewModel; } }

  private OnKeyUp()
  {
    this.ViewModel.Data.View.Refresh();
  }
}

答案 1 :(得分:3)

您可能希望从Silverlight Toolkit开始使用AutocompleteBox。

它有许多方便的点,你可以扩展它的功能,例如在搜索你的值池的实例中。