[英]Filter a CollectionViewSource and then sort manually
我有一个ObservableCollection<Recipe>
绑定到ICollectionView
。 可以通过我的个人谓词实现进行过滤。 ICollectionView
绑定在dataGrid
。
现在,我想在过滤出收藏集后重新排列Recipes
列表。
食谱具有属性“标识符”。 如果您确切输入了配方的标识符,则应将其放在列表顶部。
一个例子:
如果您在过滤器中输入1234
,则“ Identifier = 1234
的Recipe
应放在列表的顶部,而不是排在第二位。
public ICollectionView RecipeCollection
{
get => _RecipeCollection;
set
{
_RecipeCollection = value;
OnPropertyChanged();
}
}
private ICollectionView _RecipeCollection;
Recipes = new ObservableCollection<Recipe>(databaseQuery.Result);
RecipeCollection = CollectionViewSource.GetDefaultView(Recipes);
RecipeCollection.Filter = CollectionViewSource_Filter;
private bool CollectionViewSource_Filter(object item)
{
if (item is Recipe recipe)
{
if (string.IsNullOrEmpty(SearchBox.Text))
{
return true;
}
string filter = SearchBox.Text.ToLower();
if (recipe.Identifier.ToLower().Contains(filter))
{
return true;
}
if (!string.IsNullOrEmpty(recipe.Name) && recipe.Name.ToLower().Contains(filter))
{
return true;
}
if (!string.IsNullOrEmpty(recipe.Description) && recipe.Description.ToLower().Contains(filter))
{
return true;
}
}
return false;
}
您可以向Recipe
类添加SortOrder
属性SortDescription(nameof(Recipe.SortOrder), ListSortDirection.Ascending)
ICollectionView
的SortDescriptions
属性添加新的SortDescription(nameof(Recipe.SortOrder), ListSortDirection.Ascending)
。 然后,根据所需的排序顺序设置所有Recipe
对象的SortOrder
属性的值。 这应该重新排列配方列表。
根据您的要求,您可能需要使用启用了实时排序的CollectionViewSource
: https : //wpf.2000things.com/2014/01/16/988-enabling-live-sorting-in-a-collectionviewsource/
如@redcurry所指出的,如果您使用ListCollectionView
,则可以将CustomSort
属性设置为IComparer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.