Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SortDescription and automatic sorted order refresh

When I modified a value of a item which bound in listbox, I expected a sorted order should changing automatically.

But it doesn't.

Am I call a .SortDescriptions.Clear() method and reallocate a SortDescription in this case?

.Refresh() doesn't work.

EDITED

i bound and setted the data like this;

public Records myRecents;


....

//lbToday is a ListBox.
//ModifiedTime is a DateTime.
this.lbToday.ItemsSource = new ListCollectionView(myRecents);
this.lbToday.Items.SortDescriptions.Add(new SortDescription("ModifiedTime", ListSortDirection.Descending));

When the app launched in first time, it showed correct result. But when I modfying a value of item (in this case, 'ModifiedTime' property), a view doesn't changed. And I re-launched app, it showing a correct result again.

EDITED2

Here is a source code of the Records.

public class Records : ObservableCollection<RecordItem>
{
    public Records() { }

}

and here is a source code of the 'RecordItem'

public class RecordItem : INotifyPropertyChanged
{

    string queryString; public string QueryString { get { return queryString; } set { queryString = value; Notify("QueryString"); } }

    DateTime modifiedTime; public DateTime ModifiedTime { get { return modifiedTime; } set { modifiedTime = value; Notify("ModifiedTime"); } }


    public RecordItem() { }
    public RecordItem(string qStr)
    {
        this.queryString = qStr;
        this.modifiedTime = DateTime.Now;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName) { if (this.PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } }

}

Note

When I Added a Item in myRecents, (the Record class), it works well. A problem has occured only modifying a property.

like image 809
mjk6026 Avatar asked Sep 10 '11 13:09

mjk6026


2 Answers

Take a look at this article from Dr. WPF: ItemsControl: 'E' is for Editable Collection

It should help you with your problem.

like image 150
LPL Avatar answered Nov 01 '22 06:11

LPL


.NET 4.5 added two new properties to the ListCollectionView, which is the default implementation for a ListBox and CollectionViewSource.View.

To have live sorting on your ModifiedTime property, add that to the LiveSortingProperties and turn on IsLiveSorting.

list.SortDescriptions.Add(new SortDescription("ModifiedTime", ListSortDirection.Ascending));
list.IsLiveSorting = true;
list.LiveSortingProperties.Add("ModifiedTime");

This should re-sort the list when ModifiedTime changes. This has the added benefit of not refreshing the entire view!

like image 26
Shawn Kendrot Avatar answered Nov 01 '22 06:11

Shawn Kendrot