Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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





C#
        #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
Updated 9-Apr-13 4:06am
v3

Modify your Filter event handler ...
the else if part should contain
C#
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
 
Share this answer
 
v2
Got it by adding a IcollectionView property and binding the listbox to that property.


C#
public ICollectionView FilteredUsers
        {
            get
            {
                return usercvs.View;
            }
        }
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900