Выборочная сортировка в PagedCollectionview и Silverlight

Можете ли вы помочь мне настроить сортировку в silverlight с помощью PagedCollectionview, сопоставленного с observablecollection. Ниже приведен код, который работает нормально для части сортировки, но не обновляет сетку, поскольку сортировка из первого столбца не очищается

Например. если я сортирую его, используя "описание", он работает в обоих направлениях (asc & desc). но после сортировки коллекции, используя "описание", если я нажимаю на заголовок "Тип", он должен очистить более раннюю сортировку и сортировку, используя "Тип". "Только столбец.

   private void SortCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Reset)
            return;
        if (e.Action == NotifyCollectionChangedAction.Replace || e.Action == NotifyCollectionChangedAction.Add)
        {
            MyPVC.SortDescriptions.Clear();
            if (e.NewItems.Count > 0)
            {
                MyPVC.SortDescriptions.Clear();
                SortDescription sd = (SortDescription) e.NewItems[0];
                if (sd.PropertyName == "description")
                {
                    e.NewItems.Clear();
                    using (MyPVC.DeferRefresh())
                    {
                        ObservableCollection<MyClass> source = ((ObservableCollection<MyClass>)MyPVC.SourceCollection);
                        if (source == null)
                            return;
                        bool asc = (sd.Direction == ListSortDirection.Ascending);
                        var source1 = new List<MyClass>(source);
                        source1.Sort((a, b) =>
                        {
                            int left = 0;
                            int right = 0;
                            var ret = 0;
                            if (int.TryParse(a.description, out left) && int.TryParse(b.description, out right))
                            {
                                ret = (left < right) ? -1 : (left == right) ? 0 : 1;
                                if (!asc)
                                    ret = -ret;
                            }

                            return ret;
                        });

                        var newsource = new ObservableCollection<MyClass>(source1);
                        MyPVC = new PagedCollectionView(newsource);
                        ((INotifyCollectionChanged)MyPVC.SortDescriptions).CollectionChanged += SortCollectionChanged;
                        MyPVC.SortDescriptions.Clear();
                    }
                    MyClassDataGrid.ItemsSource = MyPVC;
                    MyPVC.Refresh();

                }
                if (sd.PropertyName == "Type")
                {
                    MyPVC.SortDescriptions.Clear();
                    //MyPVC = new PagedCollectionView(MyPVC);
                    e.NewItems.Clear();
                    using (MyPVC.DeferRefresh())
                    {
                        ObservableCollection<MyClass> source = ((ObservableCollection<MyClass>)MyPVC.SourceCollection);
                        if (source == null)
                            return;
                        bool asc = (sd.Direction == ListSortDirection.Ascending);
                        var source1 = new List<MyClass>(source);
                        source1.Sort((a, b) =>
                        {
                            int left = 0;
                            int right = 0;
                            var ret = 0;
                            if (int.TryParse(a.Type, out left) && int.TryParse(b.Type, out right))
                            {
                                ret = (left < right) ? -1 : (left == right) ? 0 : 1;
                                if (!asc)
                                    ret = -ret;
                            }

                            return ret;
                        });

                        var newsource = new ObservableCollection<MyClass>(source1);
                        MyPVC = new PagedCollectionView(newsource);
                        ((INotifyCollectionChanged)MyPVC.SortDescriptions).CollectionChanged += SortCollectionChanged;

                        MyPVC.SortDescriptions.Clear();
                    }
                }
            }
        }
    }
    private void MyClasstableView_ColumnHeaderClick(object sender, ColumnHeaderClickEventArgs e)
    {
        ((INotifyCollectionChanged) MyPVC.SortDescriptions).CollectionChanged += SortCollectionChanged;
    }

2 ответа

Решение

Спасибо за ваш ответ, Дейн, но в коллекции есть все данные в строковом формате, мне нужно отсортировать некоторые данные на основе даты, поэтому мне нужно использовать в ней преобразование. Поэтому мне нужны эти манипуляции. Я сделал несколько изменения в коде, так как мне нужно обновить сетку. Я использовал методы begindataupdate()-EndDataUpdate(), но это дает мне ошибку. Я считаю, что это из пользовательского интерфейса.

   private void SortCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Reset)
            return;
        if (e.Action == NotifyCollectionChangedAction.Replace || e.Action == NotifyCollectionChangedAction.Add)
        {
            MyPVC.SortDescriptions.Clear();
            if (e.NewItems.Count > 0)
            {
                MyPVC.SortDescriptions.Clear();
                SortDescription sd = (SortDescription) e.NewItems[0];
                if (sd.PropertyName == "description")
                {
                    e.NewItems.Clear();
                    using (MyPVC.DeferRefresh())
                    {
                        ObservableCollection<MyClass> source = ((ObservableCollection<MyClass>)MyPVC.SourceCollection);
                        if (source == null)
                            return;
                        bool asc = (sd.Direction == ListSortDirection.Ascending);
                        var source1 = new List<MyClass>(source);
                        source1.Sort((a, b) =>
                        {
                            int left = 0;
                            int right = 0;
                            var ret = 0;
                            if (int.TryParse(a.description, out left) && int.TryParse(b.description, out right))
                            {
                                ret = (left < right) ? -1 : (left == right) ? 0 : 1;
                                if (!asc)
                                    ret = -ret;
                            }

                            return ret;
                        });

                        var newsource = new ObservableCollection<MyClass>(source1);
                        MyPVC = new PagedCollectionView(newsource);
                        //((INotifyCollectionChanged)LeasePVC.SortDescriptions).CollectionChanged += SortCollectionChanged;

                        //LeasePVC.Refresh();
                        LeasePVC.SortDescriptions.Clear();

                        this.MyClassDataGrid.BeginDataUpdate();
                        this.MyClassDataGrid.ItemsSource = MyPVC;
                        this.MyClassDataGrid.EndDataUpdate();
                    }


                }
                if (sd.PropertyName == "Type")
                {
                    MyPVC.SortDescriptions.Clear();
                    //MyPVC = new PagedCollectionView(MyPVC);
                    e.NewItems.Clear();
                    using (MyPVC.DeferRefresh())
                    {
                        ObservableCollection<MyClass> source = ((ObservableCollection<MyClass>)MyPVC.SourceCollection);
                        if (source == null)
                            return;
                        bool asc = (sd.Direction == ListSortDirection.Ascending);
                        var source1 = new List<MyClass>(source);
                        source1.Sort((a, b) =>
                        {
                            int left = 0;
                            int right = 0;
                            var ret = 0;
                            if (int.TryParse(a.Type, out left) && int.TryParse(b.Type, out right))
                            {
                                ret = (left < right) ? -1 : (left == right) ? 0 : 1;
                                if (!asc)
                                    ret = -ret;
                            }

                            return ret;
                        });

                        var newsource = new ObservableCollection<MyClass>(source1);
                        MyPVC = new PagedCollectionView(newsource);
                        //((INotifyCollectionChanged)LeasePVC.SortDescriptions).CollectionChanged += SortCollectionChanged;

                        //LeasePVC.Refresh();
                        LeasePVC.SortDescriptions.Clear();

                        this.MyClassDataGrid.BeginDataUpdate();
                        this.MyClassDataGrid.ItemsSource = MyPVC;
                        this.MyClassDataGrid.EndDataUpdate();
                    }
                }
            }
        }
    }
    private void MyClasstableView_ColumnHeaderClick(object sender, ColumnHeaderClickEventArgs e)
    {
        ((INotifyCollectionChanged) MyPVC.SortDescriptions).CollectionChanged += SortCollectionChanged;
    }

Похоже, что вы выполняете слишком много работы здесь, чтобы реализовать простую сортировку. PagedCollectionView предназначен для фильтрации, сортировки и т. Д. Он сделает всю работу за вас. Вы правильно поняли основы, но вам не нужно делать манипуляции с исходным кодом, чтобы заставить сортировку работать.

Другие вопросы по тегам