Dan
Dan

Reputation: 209

ListBox CollectionViewSource.Filter method question

I have a listbox defined in XAML and I filter its items using the following code from text obtained from a textbox:

if (list.Items.Count > 0)
{
    CollectionViewSource.GetDefaultView(list.Items).Filter = 
        new Predicate<object>((item) => {
            string valtoCheck = item.ToString();
            return valtoCheck.StartsWith(filterText, 
                StringComparison.CurrentCultureIgnoreCase);
        });
}

Everything works fine, except in the case where the filter finds no items matching the criteria.

ex. Lets say I have 4 items in the list : Rob,Bob,Andy,John.

When I enter Ro, the list filters accordingly (shows rob).
When I enter b, the list gets filtered appropriately (shows bob).

However, if i enter z (the target list becomes empty), I get an empty list which is correct; but then List.Items.Count is set to zero from that point on. The list becomes empty. I would assume that typing a replacement b should show me Bob but it does not; the list's items are set to empty as soon as I enter text that is not contained in any of the items in the listbox!

Am I missing something here?

Upvotes: 1

Views: 961

Answers (2)

John Bowen
John Bowen

Reputation: 24453

It's hard to tell without seeing more of the surrounding code but issues like this are usually related to Refresh not being called at the right times. It also looks like you may be reassigning the Filter over and over instead of setting it once and refreshing when the filter text changes.

Upvotes: 0

Bala R
Bala R

Reputation: 108957

I dont see you cannot eliminate the if condition check and just have

 CollectionViewSource.GetDefaultView(list.Items).Filter = 
        new Predicate<object>((item) => {
            string valtoCheck = item.ToString();
            return valtoCheck.StartsWith(filterText, 
                StringComparison.CurrentCultureIgnoreCase);
        });

Upvotes: 3

Related Questions