在Silverlight中实现"在键入时搜索"

gyu*_*isc 3 silverlight silverlight-4.0

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

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

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

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

Joe*_*ide 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,你可以使用Jeff Wilcox的Highlight TextBlock.http://www.jeff.wilcox.name/2009/08/sl3-highlighting-text-block/ (2认同)