WPF ICollectionView过滤 [英] WPF ICollectionView Filtering
本文介绍了WPF ICollectionView过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在ComboBox中为过滤项目编写了一个代码: 我的问题是,你会怎么做?
>我认为这个反射的解决方案可能非常慢。
ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
view.Filter + = this.FilterPredicate;
$ b private bool FilterPredicate(object value)
{
if(value == null)
return false;
if(String.IsNullOrEmpty(SearchedText))
return true;
$ b $ int index = value.ToString()。IndexOf(
SearchedText,
0,
StringComparison.InvariantCultureIgnoreCase);
if(index> -1)返回true;
返回FindInProperties(新字符串[] {Property1,Property2},值,SearchedText);
$ b $ private bool FindInProperties(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;
$ b $ int index = s.ToString()。IndexOf(
txtToFind,
0,
StringComparison.InvariantCultureIgnoreCase);
if(index> -1)返回true;
}
返回false;
解决方案
/ p>
ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
IEqualityComparer< String> comparer = StringComparer.InvariantCultureIgnoreCase;
view.Filter = o => {
Person p = o as Person;
返回p.FirstName.Contains(SearchedText,comparer)
|| p.LastName.Contains(SearchedText,comparer);
$ b你需要动态地搜索属性吗?
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;
}
解决方案 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?
这篇关于WPF ICollectionView过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文