2011-06-27 8 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

これは少しトリッキーで、主に基礎となるデータソースに依存しますが、ここで私は何をすべきかです:

まず、何よりも、あなたがソート可能であるデータ型を必要としています。それは、データソースとして、私は私のデータグリッドの種類を検出し、実際のデータを訴えることができて、今

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); 
    } 
} 

:このため、私は私の基礎となるデータ型以降「SortableObservableCollection」を作成しましたがのObservableCollectionです。これを行うために、私は私の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を使用して組み合わせ(ソートホールドを行うためのインスタンスであるよりも少し良い作品あなたの列に並べ替えるときにシフトして、私は何を意味するか分かります)。