繁体   English   中英

筛选CollectionViewSource,然后手动排序

[英]Filter a CollectionViewSource and then sort manually

我有一个ObservableCollection<Recipe>绑定到ICollectionView 可以通过我的个人谓词实现进行过滤。 ICollectionView绑定在dataGrid

现在,我想在过滤出收藏集后重新排列Recipes列表。

食谱具有属性“标识符”。 如果您确切输入了配方的标识符,则应将其放在列表顶部。

一个例子:

  • 12345
  • 1234
  • 123

如果您在过滤器中输入1234 ,则“ Identifier = 1234Recipe应放在列表的顶部,而不是排在第二位。

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) ICollectionViewSortDescriptions属性添加新的SortDescription(nameof(Recipe.SortOrder), ListSortDirection.Ascending) 然后,根据所需的排序顺序设置所有Recipe对象的SortOrder属性的值。 这应该重新排列配方列表。

根据您的要求,您可能需要使用启用了实时排序的CollectionViewSourcehttps : //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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM