2011-06-24 132 views
7

我有一个填充了DataSet数据的WPF DataGrid。我有CanUserSortColumns设置为true在WPF DataGrid中保留用户定义的排序顺序

是否可以保留用户在网格刷新时指定的排序?我把它留住这是使用

object selectedItem = dgInvoiceHeads.SelectedItem; 

刷新发生之前,然后放置

dgInvoiceHeads.SelectedItem = selectedItem; 

刷新发生后选择的项目。

但我似乎无法得到它保留指定的排序。

回答

3

我的一位同事提出了这个问题。它似乎工作正常。唯一的事情是我认为DataGrid中的列标题需要与数据库中的列标题相同。

string sortHeader; 
string prevSortHeader; 
SortDescription sd; 

private void dgInvoiceHeads_Sorting(object sender, DataGridSortingEventArgs e) { 
    sortHeader = e.Column.Header.ToString(); 

    if (sortHeader == prevSortHeader) { 
    sd = new SortDescription(sortHeader, ListSortDirection.Descending); 
    } 
    else { 
    sd = new SortDescription(sortHeader, ListSortDirection.Ascending); 
    } 
    prevSortHeader = sortHeader; 
} 

HTH

+2

通过在列实例中使用SortMemberPath而不是Header属性,可以解决必须使头文件与类成员相同的问题。 'sortHeader = e.Column.SortMemberPath' – BrianVPS

3

以下代码是从此forum post中提取的,它显示了如何获取排序说明和列信息并将其恢复。

List<DataGridColumn> GetColumnInfo(DataGrid dg) { 
    List<DataGridColumn> columnInfos = new List<DataGridColumn>(); 
    foreach (var column in dg.Columns) { 
     columnInfos.Add(column); 
    } 
    return columnInfos; 
} 

List<SortDescription> GetSortInfo(DataGrid dg) { 
    List<SortDescription> sortInfos = new List<SortDescription>(); 
    foreach (var sortDescription in dg.Items.SortDescriptions) { 
     sortInfos.Add(sortDescription); 
    } 
    return sortInfos; 
} 

void SetColumnInfo(DataGrid dg, List<DataGridColumn> columnInfos) { 
    columnInfos.Sort((c1, c2) => { return c1.DisplayIndex - c2.DisplayIndex; }); 
    foreach (var columnInfo in columnInfos) { 
     var column = dg.Columns.FirstOrDefault(col => col.Header == columnInfo.Header); 
     if (column != null) { 
      column.SortDirection = columnInfo.SortDirection; 
      column.DisplayIndex = columnInfo.DisplayIndex; 
      column.Visibility = columnInfo.Visibility; 
     } 
    } 
} 

void SetSortInfo(DataGrid dg, List<SortDescription> sortInfos) { 
    dg.Items.SortDescriptions.Clear(); 
    foreach (var sortInfo in sortInfos) { 
     dg.Items.SortDescriptions.Add(sortInfo); 
    } 
} 
3

您是否尝试过获取数据集的collectionview?

CollectionViewSource.GetDefaultView(yourDataSet).SortDescriptions 

这会给你一个当前sortdescriptions的数组。然后您可以坚持这些,并在下一次适用他们如下

CollectionViewSource.GetDefaultView(yourDataSet).SortDescriptions.Add(...) 

希望它有帮助。

+2

没错!这应该是正确的解决方案..并且是唯一的解决方案。如果我是正确的,你甚至不必“记住”以前的排序或分组:一旦它们被声明为int的collectionViewSource,所有新增加的项目将被相应地排序,就好像你只是做了一个粗暴的动作'。刷新()'在'ICollectionView'对象上... – Bruno

1
private void testGrid_Sorting(object sender, DataGridSortingEventArgs e) 
     { 

ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ? 
           ListSortDirection.Ascending : ListSortDirection.Descending; 

// You will get the current direction in direction 

     } 

This is another solution