Issue sorting datagrid

做~自己de王妃 提交于 2019-12-12 18:16:55

问题


A technique I have used for a long time to do sorting in WPF is to create a CollectionViewSource and specifying SortDescriptions, eg

<Window.Resources>
    <CollectionViewSource x:Key="testView">
        <CollectionViewSource.SortDescriptions>
            <cm:SortDescription PropertyName="FirstName" Direction="Descending"></cm:SortDescription>
            <cm:SortDescription PropertyName="FamilyName"></cm:SortDescription>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>

This has worked perfectly for everything I've thrown at it except with the DataGrid. It appears to work fine the first time through but if I change the data then the grid kills the sorting. It even kills it for other controls that use the same CollectionViewSource. I've created a sample project here

http://www.mikesdriveway.com/misc/GridSortIssue.zip

To test this issue run the project and click the Refresh Data button. Notice that the order of items changes. This only happens once, to test again stop and run the project again. Now delete the ItemsSource from the DataGrid and run the project again. This time when you click the Refresh Data button nothing happens, this means the sorting remains the same. Somehow the grid is killing the sorting in the CollectionViewSource. Is this a bug?

Cheers, Michael


回答1:


That is rather odd, from what i can tell the SortDescription of the underlying View get cleared out when the source is changed, so if the SortDescriptions of the CVS are not re-applied there is no sorting anymore.

One workaround would be to "reset" the SortDescriptions:

var cvs = (CollectionViewSource)Resources["testView"];
var descriptions = cvs.SortDescriptions.ToArray();
cvs.SortDescriptions.Clear();
foreach (var descripton in descriptions) cvs.SortDescriptions.Add(descripton);


来源:https://stackoverflow.com/questions/9560528/issue-sorting-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!