如何在列表视图中搜索和过滤关闭字符串。
例如,我的列表视图中有两列,并且都是可绑定的。
假设第一列名为bindlname,第二列名为“ bindfname ”
例如这是我的列表视图记录:
现在,如果我输入“ Y并点击搜索按钮。它将过滤YU ZIQ 和 FEAGS YAPSLE 姓氏 中的所有第一个字母,并且以字母“ Y ”开头的名字将被过滤......如果每个我都会输入“ UY ”它将显示UY QILUZ 和 UY ZKAE
您可以使用ICollectionView
将数据绑定到ListView
,当您按下按钮时,您可以过滤此数据。
示例代码:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
public class MainViewModel : NotificationObject
{
public MainViewModel()
{
SearchPerson = new DelegateCommand(this.OnSearchPerson);
// test data
_myDataSource.Add(new Person { Name = "John", Surname = "Blob" });
_myDataSource.Add(new Person { Name = "Jack", Surname = "Smith" });
_myDataSource.Add(new Person { Name = "Adam", Surname = "Jackson" });
}
private List<Person> _myDataSource = new List<Person>();
private string _searchString;
public string SearchString
{
get { return _searchString; }
set { _searchString = value; RaisePropertyChanged(() => SearchPerson); }
}
private ICollectionView _people;
public ICollectionView People
{
get { return CollectionViewSource.GetDefaultView(_myDataSource); }
}
public ICommand SearchPerson { get; private set; }
private void OnSearchPerson()
{
if (!string.IsNullOrEmpty(SearchString))
{
People.Filter = (item) => { return (item as Person).Name.StartsWith(SearchString) || (item as Person).Surname.StartsWith(SearchString) ? true : false; };
}
else
People.Filter = null;
}
}
XAML 文件:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding SearchString}" Width="150" />
<Button Content="Search" Command="{Binding SearchPerson}" />
</StackPanel>
<ListView Grid.Row="1" ItemsSource="{Binding People}">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Surname" DisplayMemberBinding="{Binding Surname}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
</Grid>
这是完整的示例(ListViewSearch.zip)。