Home > OS >  EmptySortDescriptionCollection with SortDescriptions
EmptySortDescriptionCollection with SortDescriptions

Time:06-23

I am about to sort the ObservableCollection from database retrieved by EF Core in code-behind (not in front-end).

Here is the class of the model:

public class BindDesignModel : INotifyPropertyChanged
{
        [Key]
        public string id { get; set; }
        string _code;

        public string code
        {
            get => _code; set
            {
                _code = value;
                OnPropertyChanged();
            }
        }
        public string DesignFileName { get; set; }
        string _name;
        [NotMapped]
        public string name
        {
            get => _name;
            set
            {
                _name = value;
                OnPropertyChanged();
            }
        }

        [NotMapped]
        public Boolean IsBinded => !string.IsNullOrEmpty(code);

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
}

The property IsBinded is just for sorting the ObservableCollection.

And here is the code

Database.Context Context = new Database.Context();
CollectionView CV = new CollectionView(Context.BindDesign.Local.ToObservableCollection());            
BindDesignIC.ItemsSource = CV;            
CV.SortDescriptions.Add(new SortDescription("IsBinded", ListSortDirection.Ascending));

The BindDesignIC is an ItemsControl and it can run without any error if bind the ObservableCollection directly.

However, after the code above ran, it reports this error:

System.NotSupportedException
HResult=0x80131515
Message=Specified method is not supported.
Source=WindowsBase

StackTrace:
at System.ComponentModel.SortDescriptionCollection.EmptySortDescriptionCollection.InsertItem(Int32 index, SortDescription item)

What's wrong with my code? Thank you.

CodePudding user response:

Don't explicitly create a CollectionView.

WPF creates one for you and you can get a reference to it using the CollectionViewSource.GetDefaultView method:

dg.ItemsSource = Context.BindDesign.Local.ToObservableCollection();
ICollectionView CV = CollectionViewSource.GetDefaultView(dg.ItemsSource);
CV.SortDescriptions.Add(new SortDescription("IsBinded", ListSortDirection.Ascending));
  • Related