在listview中搜索字符串和过滤器

时间:2012-11-11 00:16:00

标签: c# wpf listview filtering

如何在listview中搜索和过滤关闭字符串。

例如我的listview中有两列,两者都是可绑定的。

假设第一列名为 bindlname ,第二列名称为“ bindfname

例如这是我的listview记录:

enter image description here

现在,如果我输入“ Y 并点击搜索按钮。它将过滤 YU ZIQ和FEAGS YAPSLE 姓氏中的所有首字母和以字母“ Y ”开头的名字将被过滤...如果我每次输入“ UY ”,则会显示 UY QILUZ和UY ZKAE

1 个答案:

答案 0 :(得分:4)

您可以使用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>

Here是完整示例(ListViewSearch.zip)。