2010-07-27 2 views
9

У меня проблема с набором инструментов wpf DataGrid.wpf set sorting программно, так что заголовок переключается как отсортированный

У меня есть ItemsSource с три колонки:

FirstName

LastName

Адрес

В C# коде я установить направление сортировки и какой столбец для сортировки так:

ICollectionView view = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource); 
view.SortDescriptions.Clear(); 
view.SortDescriptions.Add(new SortDescription("LastName", ListSortDirection.Ascending)); 
view.Refresh(); 

Ther e не проблема в фактической сортировке, но в визуальном стиле заголовков. Если пользователь сортирует столбец, нажимая на заголовок, визуальный стиль изменяется, но визуальный стиль не указывает, что описание сортировки столбца задано программно.

Почему это и как я могу переключать заголовок, чтобы он отображался как отсортированный?

ответ

12

Я еще не пробовал, но я мог бы подумать, что вы можете установить свойство SortDirection для столбца.

  int columnIndex = 0; 
      this.dataGrid1.ColumnFromDisplayIndex(columnIndex).SortDirection = 
       ListSortDirection.Descending; 
+0

К сожалению, я получаю эту ошибку: Данный DisplayIndex находится вне диапазона. – Cinaird

+0

Хорошо, я был немного неряшлив, и он отлично работает! Спасибо – Cinaird

1

Ниже образца позволит вам отсортировать таблицу данных, используя выпадающие списки, а также щелкнув непосредственно на сетке.

XAML:

<Window x:Class="DataGridDemo.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" 
    xmlns:System="clr-namespace:System;assembly=mscorlib" 
    xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=System" 
    Height="300" Width="300"> 

    <Window.Resources> 
     <ObjectDataProvider MethodName="GetValues" 
      ObjectType="{x:Type System:Enum}" 
      x:Key="SortDirections"> 
      <ObjectDataProvider.MethodParameters> 
       <x:Type TypeName="ComponentModel:ListSortDirection" /> 
      </ObjectDataProvider.MethodParameters> 
     </ObjectDataProvider> 
    </Window.Resources> 

    <StackPanel> 
     <ComboBox 
      Name="_columnsComboBox" 
      ItemsSource="{Binding Path=Columns, ElementName=_dataGrid}" 
      DisplayMemberPath="Header" 
      SelectionChanged="OnSort" /> 
     <ComboBox 
      Name="_sortDirectionsComboBox" 
      ItemsSource="{Binding Source={StaticResource SortDirections}}" 
      SelectionChanged="OnSort" /> 
     <Controls:DataGrid 
      Name="_dataGrid" 
      ItemsSource="{Binding Path=PeopleData}" /> 

    </StackPanel> 
</Window> 

Код позади:

using System; 
using System.ComponentModel; 
using System.Data; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using Microsoft.Windows.Controls; 

namespace DataGridDemo 
{ 
    /// <summary> 
    /// Interaction logic for Window1.xaml 
    /// </summary> 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 

      PeopleData = new DataTable(); 
      PeopleData.Columns.Add(new DataColumn("Name", typeof(string))); 
      PeopleData.Columns.Add(new DataColumn("Age", typeof(int))); 

      var row = PeopleData.NewRow(); 
      row["Name"] = "Sara"; 
      row["Age"] = 25; 
      PeopleData.Rows.Add(row); 

      row = PeopleData.NewRow(); 
      row["Name"] = "Bob"; 
      row["Age"] = 37; 
      PeopleData.Rows.Add(row); 

      row = PeopleData.NewRow(); 
      row["Name"] = "Joe"; 
      row["Age"] = 10; 
      PeopleData.Rows.Add(row); 

      DataContext = this; 
     } 

     public DataTable PeopleData { get; private set;} 

     private void OnSort(object sender, SelectionChangedEventArgs e) 
     { 
      if (_sortDirectionsComboBox.SelectedIndex == -1 || _columnsComboBox.SelectedIndex == -1) 
      { 
       return; 
      } 

      foreach (DataGridColumn dataColumn in _dataGrid.Columns) 
      { 
       dataColumn.SortDirection = null; 
      } 

      ListSortDirection sortDescription = (ListSortDirection)(_sortDirectionsComboBox.SelectedItem); 
      DataGridColumn selectedDataColumn = _columnsComboBox.SelectedItem as DataGridColumn; 
      selectedDataColumn.SortDirection = sortDescription; 

      ICollectionView view = CollectionViewSource.GetDefaultView(_dataGrid.ItemsSource); 
      view.SortDescriptions.Clear(); 
      view.SortDescriptions.Add(new SortDescription(selectedDataColumn.Header as string, sortDescription)); 
      view.Refresh(); 
     } 
    } 
} 
+0

К сожалению, доза не помогает мне сортировать список на загруженном окне, и это моя проблема. – Cinaird

+0

Просто возьмите код в OnSort и введите его в метод, который принимает столбцы для сортировки и сортировки. –