2013-06-06 19 views
17

WPF DataGridをプログラム的にソートする方法はありますか(たとえば、最初の列をクリックした場合など)。wpfデータグリッドをプログラムで並べ替える

このクリックをシミュレートする方法はありますか?または最善の方法?ここで

は私のコードです:

Collection_Evenements = new ObservableCollection<Evenement>(); 

Collection_Evenements = myEvenement.GetEvenementsForCliCode(App.obj_myClient.m_strCode); 
Collection_Evenements.CollectionChanged += Collection_Evenements_CollectionChanged; 
myDataGridEvenements.ItemsSource = Collection_Evenements; 

System.Data.DataView dv = (System.Data.DataView)myDataGridEvenements.ItemsSource; 
dv.Sort = "strEvtType"; 

myDataGridEvenements.Focus(); 
myDataGridEvenements.SelectedIndex = 0; 
myDataGridEvenements.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); 

私はなぜ知っているが、ライン "dv.Sort = "strEvtTypeません";"奇妙なことが起こり、私のウィンドウショーアップとプログラムは次の行を実行し続けることはありませんが、それでもソートは表示されません!

どうもありがとう、

敬具、

Nixeus

+0

あなたはあなたのデータグリッドビューを並べ替えることができませんか?レイアウトをリフレッシュしますか? – Alex

+1

お願いしますか?これはどうやって?ありがとう –

答えて

7

あなたのItemsSourceのデータビューを取得し、あなたがでソートされている列を指定するために、そのSortプロパティを使用します。

(yourDataGrid.ItemsSource as DataView).Sort = "NAME_OF_COLUMN"; 
+0

こんにちは、答えに感謝します。列の名前は "header"プロパティですか?私は名前のプロパティを見つけられませんでした:( –

+0

@WalterFabioSimoniいいえ、あなたのDataGridにバインドするソースの列の名前です。 – Alex

+0

わかりました!しかし、プログラムが.Sort行に行くと、私はプログラムのウィンドウを表示すると、それはすべて!それは奇妙です –

0

をおICollectionViewを使用して、データグリッド内の項目をフィルタリング、並べ替え、グループ化することができます。

EDIT:慎重に質問を読んでいない:)それが直接設定されますが、バインドされていなかったため

var view = CollectionViewSource.GetDefaultView(this.MyData); 
view.Filter = ViewFilter; 
view.SortDescriptions.Add(new SortDescription("MyPropertyToSort", ListSortDirection.Descending)); 


    private bool ViewFilter(object obj) 
    { 
     var item = obj as MyObject; 

     if (item == null) 
      return false; 

     //your filter logik goes here 

     if(item.MyStringProp.StartsWith("Test")) 
      return false; 

     return true; 


    } 
+0

オブジェクトコレクションにバインドするのではなくデータテーブルにバインドしない場合は、IBindingListView.Filter(http://msdn.microsoft.com/de-de/library/system.componentmodel.ibindinglistview_members(v=vs.80)を使用する必要があります。 .aspx) – blindmeis

29

VOOのソリューションは、ItemsSourceがnullだった、私のために働い最もありそうでなかった、ソートを追加します。 ここで私がStackOverflowで見つけた他のすべてのソリューションはモデルのみのソートを扱っていましたが、DataGridヘッダーはソートに反映されていませんでした。

はここ、ここ、不完全なスクリプトに基づいて適切なソリューションです:

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending); 

またはデフォルトパラメータ値を使用して:あなたのコードの場合はhttp://dotnetgui.blogspot.co.uk/2011/02/how-to-properly-sort-on-wpf-datagrid.html

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending) 
{ 
    var column = dataGrid.Columns[columnIndex]; 

    // Clear current sort descriptions 
    dataGrid.Items.SortDescriptions.Clear(); 

    // Add the new sort description 
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection)); 

    // Apply sort 
    foreach (var col in dataGrid.Columns) 
    { 
     col.SortDirection = null; 
    } 
    column.SortDirection = sortDirection; 

    // Refresh items to display sort 
    dataGrid.Items.Refresh(); 
} 

、それはこのように使用することができます簡単に:

SortDataGrid(myDataGridEvenements); 
+0

驚くばかりの方法で、使いやすく変更が容易です。ありがとう。 –

0

私の方法は私の仕事です。 このコードを試してみてください。申し訳ありませんが、ロシア

// Если таблица пустая, то привязываем ее к журналу 
      if(dgEvents.ItemsSource == null) 
       dgEvents.ItemsSource = events.Entries; 
      // Обновляем записи 
      CollectionViewSource.GetDefaultView(dgEvents.ItemsSource).Refresh(); 
      // Очищаем описание сортировки 
      dgEvents.Items.SortDescriptions.Clear(); 
      // Созадем описание сортировки 
      dgEvents.Items.SortDescriptions.Add(new SortDescription(dgEvents.Columns[0].SortMemberPath, ListSortDirection.Descending)); 

      // Очищаем сортировку всех столбцов 
      foreach (var col in dgEvents.Columns) 
      { 
       col.SortDirection = null; 
      } 
      // Задаем сортировку времени по убыванию (последняя запись вверху) 
      dgEvents.Columns[0].SortDirection = ListSortDirection.Descending; 
      // Обновляем записи 
      dgEvents.Items.Refresh(); 
0

PerformSort用のDataGridの方法は、実際には、列のヘッダーをクリックで実行するものです。しかし、この方法は内部的なものです。だから、あなたが本当ににしたい場合は、リフレクションを使用する必要がクリックをシミュレート:

public static void SortColumn(DataGrid dataGrid, int columnIndex) 
{ 
    var performSortMethod = typeof(DataGrid) 
          .GetMethod("PerformSort", 
             BindingFlags.Instance | BindingFlags.NonPublic); 

    performSortMethod?.Invoke(dataGrid, new[] { dataGrid.Columns[columnIndex] }); 
} 
関連する問題