在Datagrid WPF C#中仅显示项目的子集

时间:2019-03-19 16:28:51

标签: c# .net wpf xaml

因此,这并不是真正的问题,而是我过去三天遇到的问题的解决方案,我们欢迎任何改进。因此,我有一个显示所选产品的数据网格,每个产品还可以包含称为配料的子项,这些配料应添加到集合中,但不显示给用户。

我为此提出的解决方案如下。注释掉where子句是我的第一次尝试。

public ObservableCollection<ProductSaleTransaction> gProductSale = new ObservableCollection<ProductSaleTransaction>();        
        public ObservableCollection<ProductSaleTransaction> ProductSaleCollection
        {
            get { return gProductSale/*.Where(s => s.category != "Ingredients").ToObservableCollection<ProductSaleTransaction>()*/; }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {    
                    dgProductTchSale.ItemsSource = ProductSaleCollection;
                    ProductSaleCollection.CollectionChanged += ProductSaleCollection_CollectionChanged;
        }
        private void ProductSaleCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
                 ICollectionView view = CollectionViewSource.GetDefaultView(ProductSaleCollection);
                    view.Filter = new Predicate<object>(filterIngredient);
        }
public bool filterIngredient(object item)
{
        var vaitem = (ProductSaleTransaction)item;
        if (vaitem == null)
            return false;
        else
        {
            bool it = false;
            it = vaitem.category != "Ingredient";
            return it;          
        }                        
}

这将导致所有项目添加到集合中,但只有不在“成分”类别中的项目才会显示给用户。

这就是我想解决的问题,它可以自动过滤要保存的所有下游代码但不向用户显示的项目。

1 个答案:

答案 0 :(得分:0)

ICollectionView的过滤器在其基础集合添加/删除项目时会自动评估。因此,您无需每次集合更改时都创建新的ICollectionView

改为移动行

ICollectionView view = CollectionViewSource.GetDefaultView(ProductSaleCollection);
view.Filter = new Predicate<object>(filterIngredient);

自行Window_Loaded并删除ProductSaleCollection_CollectionChanged事件。