SortDescription和自动排序顺序刷新

6
当我修改绑定在列表框中的项目的值时,我期望排序顺序应该自动更改。
但实际上并没有。
在这种情况下,我需要调用 .SortDescriptions.Clear() 方法并重新分配 SortDescription 吗?
.Refresh() 无效。 编辑 我是这样绑定和设置数据的;
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));

当应用程序第一次启动时,它显示了正确的结果。但是当我修改项目的值(在这种情况下为“ModifiedTime”属性)时,视图没有更改。然后我重新启动了应用程序,它再次显示了正确的结果。
EDITED2: 这是Records的源代码。
public class Records : ObservableCollection<RecordItem>
{
    public Records() { }

}

这里是'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)); } }

}

注意

当我在myRecents(Record类)中添加一个项目时,它工作正常。只有修改属性时才会出现问题。


你能展示一下你是如何将数据绑定到UI控件上的吗? - Davide Piras
2个回答

6

6

.NET 4.5新增了两个属性到ListCollectionView中,它是ListBox和CollectionViewSource.View的默认实现。

如果想要在你的ModifiedTime属性上进行实时排序,需要将其添加到LiveSortingProperties中并开启IsLiveSorting

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

这应该在ModifiedTime更改时重新排序列表。这样做的附加好处是不会刷新整个视图!

谢谢,它起作用了!我们可以通过使用 MyCollectionView = (ListCollectionView) CollectionViewSource.GetDefaultView(MyObservableCollection); 从 ObservableCollection 中获取 ListCollectionView。 - Elo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接