2011-06-27 42 views
1

我有一個實時更新的簡單集合。數據顯示在WPF中的DataGrid中。當用戶對DataGrid進行排序並且數據發生更改時,網格將使用新數據進行更新,但不會使用數據。WPF DataGrid中的度假村數據

當底層集合發生變化時,任何人都可以找到一種很好的方式來獲取數據?我可以很容易地確定何時發生收集變化,但到目前爲止,我還沒有取得太大的成功。

發現我可以這樣做:

SortDescription description = grdData.Items.SortDescriptions[0]; 
grdData.ItemsSource = null; 
grdData.ItemsSource = Data; 
grdData.Items.SortDescriptions.Add(description); 

if(description.PropertyName=="Value") 
{ 
    grdData.Columns[1].SortDirection = description.Direction; 
} 
else 
{ 
    grdData.Columns[0].SortDirection = description.Direction; 
} 

但是它是相當的黑客。有什麼更好的東西?

回答

1

這是一個有點棘手,在很大程度上依賴的基礎數據源,但這裏是我做的:

首先,也是最重要的,你需要的是一個可排序的數據類型。對於這一點,我創建了一個「SortableObservableCollection」因爲我的基本數據類型是一個ObservableCollection:

public class SortableObservableCollection<T> : ObservableCollection<T> 
{   
    public event EventHandler Sorted;  

    public void ApplySort(IEnumerable<T> sortedItems) 
    { 
     var sortedItemsList = sortedItems.ToList(); 

     foreach (var item in sortedItemsList) 
      Move(IndexOf(item), sortedItemsList.IndexOf(item));  

     if (Sorted != null) 
      Sorted(this, EventArgs.Empty); 
    } 
} 

現在,與作爲數據源,我能察覺我的DataGrid的種類和採取的實際數據。要做到這一點,我已經添加下面的事件處理程序,以我的DataGrid的物品CollectionChanged事件:

... In the constructor or initialization somewhere 

ItemCollection view = myDataGrid.Items as ItemCollection; 
((INotifyCollectionChanged)view.SortDescriptions).CollectionChanged += MyDataGrid_ItemsCollectionChanged; 

... 

private void MyDataGrid_ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
{ 
    // This is how we detect if a sorting event has happend on the grid. 
    if (e.NewItems != null && 
     e.NewItems.Count == 1 && 
     (e.NewItems[0] is SortDescription)) 
    { 
     MyItem[] myItems = new MyItem[MyDataGrid.Items.Count]; // MyItem would by type T of whatever is in the SortableObservableCollection 
     myDataGrid.Items.CopyTo(myItems, 0); 
     myDataSource.ApplySort(myItems); // MyDataSource would be the instance of SortableObservableCollection 
    } 
} 

的原因之一這部作品不是使用SortDirection在做着合併排序的實例(持有好一點在對列進行排序時向下移動,你會看到我的意思)。