从xaml对wpf datagrid中的列标题进行排序

时间:2014-07-14 12:38:00

标签: c# sql wpf xaml datagrid

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

我有我的xaml datagrid:

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

可以说,下一栏会有DataTable

  • B栏
  • A列
  • D Column
  • C Column

我需要一种通过xaml按字母顺序表示它们的方法:

  • A列
  • B栏
  • C Column
  • D Column

我已经尝试过:

  1. 具有可排序属性的集合视图源:
  2. <CollectionViewSource x:Key="ColumnsDatagridViewSource" Source="{Binding Data}">
        <CollectionViewSource.SortDescriptions>
            <componentModel:SortDescription PropertyName="ColumnHeader"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
    

    没有帮助,一个阵列发生了。它尝试在列标题字符串中找到此属性。

    1. IValue转换器,它帮助我进行树视图排序:
    2. 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;
      }
      

2 个答案:

答案 0 :(得分:3)

由于您是自动生成列,我认为最好的方法是使用DataGrid.AutoGeneratingColumn Event

我想出了这段代码 - 小心,未经过充分测试 - 按字母顺序对列重新排序:

<强> XAML

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

<强>代码隐藏

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

不使用dg_AutoGeneratingColumn输出

Output without using dg_AutoGeneratingColumn

使用dg_AutoGeneratingColumn输出:

Output using dg_AutoGeneratingColumn

答案 1 :(得分:0)

如果有人对我的表现感兴趣:

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

我添加IValueConverter进行排序,没什么特别的,需要重构,但你可以得到一个想法:

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

此代码的作用:

首先,我从datatable获取列名,然后按照我需要的顺序对它们进行排序。 接下来,我在列上使用内置的SetOrdinal方法,将其置于正确的位置。