简体   繁体   中英

Sort column headers in wpf datagrid from xaml

public DataTable Data
{
    get { return _tableData; }
    set
    {
        if (Equals(value, _tableData)) return;
        _tableData = value;
        NotifyOfPropertyChange();
    }   
}

And I have my xaml datagrid:

<DataGrid
  HorizontalAlignment="Stretch" 
  IsReadOnly="True" ItemsSource="{Binding Data}" 
  AutoGenerateColumns="True">
</DataGrid>

Lets say, there is a DataTable will next columns:

  • B Column
  • A Column
  • D Column
  • C Column

I need a way to represent them in alphabetical order via xaml :

  • A Column
  • B Column
  • C Column
  • D Column

What I already tried:

  1. Collection view source with sortable property:
 <CollectionViewSource x:Key="ColumnsDatagridViewSource" Source="{Binding Data}"> <CollectionViewSource.SortDescriptions> <componentModel:SortDescription PropertyName="ColumnHeader"/> </CollectionViewSource.SortDescriptions> </CollectionViewSource> 

Does not help, an array occured. It tries to find this property in column header string.

  1. IValue converter, which helped me with treeview sorting:
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { System.Collections.IList collection = value as System.Collections.IList; ListCollectionView view = new ListCollectionView(collection); SortDescription sort = new SortDescription(parameter.ToString(), ListSortDirection.Ascending); view.SortDescriptions.Add(sort); return view; } 

Since you're auto generating columns, I think the best way to do it is using the DataGrid.AutoGeneratingColumn Event .

I came up with this code-- careful, not fully tested --to reorder the columns in alphabetical order:

XAML

<DataGrid ItemsSource="{Binding Data}"
          AutoGenerateColumns="True"
          AutoGeneratingColumn="dg_AutoGeneratingColumn" />

Code-behind

public class DataItem
{
    public string Name { get; set; }
    public string Ask { get; set; }
    public string Date { get; set; }
    public string Zulu { get; set; }
    public DataItem(string n, string a, string d, string z)
    {
        Name = n;
        Ask = a;
        Date = d;
        Zulu = z;
    }
}

public partial class MainWindow : Window
{
    ObservableCollection<DataItem> data = new ObservableCollection<DataItem>();
    public ObservableCollection<DataItem> Data
    {
        get
        {
            return data;
        }
    }
    public MainWindow()
    {
        Data.Add(new DataItem("A", "No", "07/14", "?"));
        Data.Add(new DataItem("B", "Yes", "07/14", "!"));
        Data.Add(new DataItem("C", "Tes", "07/14", "*"));
        Data.Add(new DataItem("D", "No", "07/14", "%"));
        InitializeComponent();
        this.DataContext = this;
    }

    private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        DataGrid dg = sender as DataGrid;
        if (dg != null && e != null)
        {
            DataGridColumn currentColumn = e.Column;
            if (currentColumn != null)
            {
                string currentHeader = currentColumn.Header.ToString();

                int currentIndex = 0;

                // Sort the Columns by name so we add the new column to the correct index
                foreach (DataGridColumn dgc in (dg.Columns.OrderBy(col => col.Header.ToString())))
                {
                    if (currentHeader.CompareTo(dgc.Header.ToString()) < 0)
                    {
                        // set the current columns
                        currentColumn.DisplayIndex = currentIndex;

                        // short-circuit the loop so we don't keep comparing after we already
                        // found the correct index to place the current column
                        break;
                    }

                    currentIndex++;
                }
            }
        }
    }
}

Output without using dg_AutoGeneratingColumn :

不使用dg_AutoGeneratingColumn输出

Output using dg_AutoGeneratingColumn :

使用dg_AutoGeneratingColumn输出

If anyone is interested in how I did it:

<DataGrid
  HorizontalAlignment="Stretch" 
  IsReadOnly="True"
  IsReadOnly="True" ItemsSource="{Binding Data, Converter={StaticResource DataGridSortingConverter}}" 
  AutoGenerateColumns="True">
</DataGrid>

I added IValueConverter for sorting, nothing special and needs refactoring, but you can get an idea:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            var dataTable = value as DataTable;

            if (dataTable != null)
            {
                var columnsList = (from object column in dataTable.Columns select column.ToString()).ToList();

                columnsList = columnsList.OrderBy(col => col).ToList();

                for (var i = 0; i < columnsList.Count; i++)
                {
                    dataTable.Columns[columnsList[i]].SetOrdinal(i);
                }

                return dataTable;
            }

            return value;
        }

What this code does:

First I get column names from datatable and then sort them in order I need. Next, I use built-in SetOrdinal method on column, which puts it in right position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM