WPF ICollectionView 过滤

5

我已经编写了一个用于在ComboBox中过滤项目的代码:

我的问题是,你会怎么做呢?

我认为这种使用反射的解决方案可能非常慢。

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;
}
1个回答

7

为什么不就这样:

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); 
                   }

您需要动态搜索属性吗?


我不知道底层的ItemSource会是什么。它必须适用于每个对象。 - theSpyCry
该控件的用户必须被赋予选择搜索方式的可能性。 - theSpyCry
好的,那么,是的,反射是你唯一能够完成这个任务的方式。我认为在处理数万或数十万个对象之前,你的性能应该还可以。如果你的测量性能不足以满足用户需求,你可以在你搜索的类型上实现IReflect,这可能会加快速度。 - codekaizen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接