WPF ICollectionView Filtering
Asked Answered
M

1

5

I've written a code for filtering items in ComboBox:

My question is, how would you do that?

I think that this solution with reflection could be very slow..

ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
view.Filter += this.FilterPredicate;


private bool FilterPredicate(object value)
{            
    if (value == null)
        return false;

    if (String.IsNullOrEmpty(SearchedText))
        return true;            

    int index = value.ToString().IndexOf(
        SearchedText,
        0,
        StringComparison.InvariantCultureIgnoreCase);

    if ( index > -1) return true;

    return FindInProperties(new string[] { "Property1", "Property2" }, value, SearchedText);
}

private bool FindInProperties(string[] properties, object value, string txtToFind)
{
    PropertyInfo info = null;
    for (int i = 0; i < properties.Length; i++)
    {
        info = value.GetType().GetProperty(properties[i]);
        if (info == null) continue;

        object s  = info.GetValue(value, null);
        if (s == null) continue;

        int index = s.ToString().IndexOf(
            txtToFind,
            0,
            StringComparison.InvariantCultureIgnoreCase);

        if (index > -1) return true;
    }
    return false;
}
Marcasite answered 26/1, 2010 at 16:44 Comment(0)
I
7

Why not just this:

ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
IEqualityComparer<String> comparer = StringComparer.InvariantCultureIgnoreCase;
view.Filter = o => { 
                     Person p = o as Person; 
                     return p.FirstName.Contains(SearchedText, comparer) 
                            || p.LastName.Contains(SearchedText, comparer); 
                   }

Do you need to search properties dynamically?

Irritative answered 26/1, 2010 at 16:50 Comment(3)
I don't know what the underlying ItemSource is going to be. It has to work for every objectMarcasite
The user of that Control must be given a possibility to choose how to search.Marcasite
Well, then, yea, reflection is about the only way you are going to accomplish this. I think you'll probably be ok, performance-wise, unless you are dealing with 10s or 100s of thousands of objects. You could implement IReflect on the type you are searching, and this might speed things up, if your measured performance is inadequate for user needs.Irritative

© 2022 - 2024 — McMap. All rights reserved.