3

我有一个 ListView,我在后面的代码中绑定到 CollectionViewSource:

collectionView = CollectionViewSource.GetDefaultView(TableView.ItemsSource);
collectionView.SortDescriptions.Clear();
collectionView.SortDescriptions.Add(new SortDescription(propertyName, direction));

TableView就是ListView,propertyName就是我要排序的列名,方向是升序或者降序。

XAML 对 ItemSource 具有以下内容:

ItemsSource="{Binding Rows}"

后面的代码对行有以下内容:

List<TableRow> rows;

public List<TableRow> Rows
{
    get { return rows; }
    set 
    {
        rows = value;
        UpdateProperty("Rows");
    }
}

更新如下:

public void Update()
{
     ...generate a list of rows...

     Rows = ...rows...
}

调用 Update 时会出现问题,列表视图会更新,但会丢失之前在 CollectionViewSource 上设置的排序。

4

4 回答 4

4

如果您正在“更新”行,那么之前行上的任何设置都将消失。如果您清除(不是新的)行,那么我认为它们将保留该设置。

而且您甚至不希望更新中的行 = 行。然后在分配行之后。

NotifyPropertyChange("Rows"); 

所以 UI 知道要更新

如果你要去新的然后重新分配

collectionView = CollectionViewSource.GetDefaultView(TableView.ItemsSource);
collectionView.SortDescriptions.Clear();
collectionView.SortDescriptions.Add(new SortDescription(propertyName, direction));

Maybe

private List<TableRow> rows = new List<TableRow>();  

and have that the only place you new it

于 2012-04-11T16:12:25.637 回答
2

The answer is to reapply the sort descriptions after the update, as in:

collectionView = CollectionViewSource.GetDefaultView(TableView.ItemsSource);  
collectionView.SortDescriptions.Clear();
collectionView.SortDescriptions.Add(new SortDescription(propertyName, direction));

Then the sorting isn't lost. Refresh on the collection view doesn't help.

于 2012-04-12T10:43:10.357 回答
2

If an item property value involved in one of the grouping, sorting and filtering operations is updated, then the sorting/grouping/filtering will not be done again.

WPF 4.5 introduce a feature called live shaping which shapes the collection view in live.

See this article for more info.

于 2013-01-14T11:23:58.063 回答
0

Did you try to do CollectionView.Refresh() after your update?

If this does not help then I think your problem occurs because you change the source of your CollectionView by assigning new value to your Rows list.

I don't know if it is possible to your code but don't assign new list just clear your previous one and insert new rows there.

if (Rows != null)
   Rows.Clear();
   Rows.TrimExcess();
else
   Rows = new List<TableRow>();
于 2012-04-12T09:08:44.837 回答