Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WPF Csharp.net , +
I have a listbox in WPF where users firstname and lastname are listed. I have a textbox, and I am trying to filter as I type by the names. Here is what I am trying: (Nothing is being filtered when I am typing in the textbox)
 
Here is my VM
 

 

 
        #region Members
 
        
        private ObservableCollection<User> mUser = new ObservableCollection<User>();
        private CollectionViewSource usercvs = new CollectionViewSource();
        private string searchString;
        
        
        #endregion
 
        #region Properties
 
        public ObservableCollection<User> Users
        {
            get
            {
                return mUser;
            }
        }
 
        public string SearchFilter
        {
            get
            {
                return this.searchString;
            }
 
            set
            {
                if (!string.IsNullOrEmpty(this.searchString))
                    AddFilter();
 
                usercvs.View.Refresh(); 
 
                this.searchString = value;
            }
        }
        
        #endregion
      
 
        #region Methods
             
        private void AddFilter()
        {
            usercvs.Filter -= new FilterEventHandler(Filter);
            usercvs.Filter += new FilterEventHandler(Filter);
 
        }
 
        private void Filter(object sender, FilterEventArgs e)
        {
            // see Notes on Filter Methods:
            var src = e.Item as User;
            if (src == null)
                e.Accepted = false;
            else if (src.LastName != null && !src.LastName.Contains(SearchFilter))
                e.Accepted = false;
        }
 
        #endregion
    }
}
Posted 8-Apr-13 17:03pm
Edited 9-Apr-13 5:06am
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Modify your Filter event handler ...
the else if part should contain
e.accepted = src.LastName.Contains(SearchFilter);
 

set e.Accepted = false; for all conditions which you want to filter and
set e.Accepted = true; for others
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Got it by adding a IcollectionView property and binding the listbox to that property.
 

public ICollectionView FilteredUsers
        {
            get
            {
                return usercvs.View;
            }
        }
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 9 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100