Сортировка DataGridTextColumn по значению Int или Float вместо сортировки необработанных строк - PullRequest
1 голос
/ 30 октября 2019

Я использую DataGrid и программно генерирую столбцы с выделенным кодом. Столбцы получены из DataGridTextColumn с некоторыми дополнениями для блокировки ввода ключа для определенного типа.

Мне нужны столбцы для числовой сортировки:

1
2
10
11

вместо сортировки по умолчанию на основе строк:

1
10
11
2

Я пробовал DataGridSortingEvent, но он не может привести к преобразованию из BindingListCollectionView в IList

ListCollectionView lcv = new ListCollectionView((IList)CollectionViewSource.GetDefaultView(dataGrid.ItemsSource));

Вот как я создаю DataGrid

DataSet set = new DataSet();
set.ReadXml(xmlDocument.CreateReader());

DataView data = set.Tables["row"];

dataGrid.ItemsSource = data;

Вот блок, в котором я создаю столбцы

dataGrid.Columns.Add(new DataChimpIntegerColumn()
                            {
                                Header = column.ColumnTitle,
                                Binding = new Binding(column.ColumnTitle),
                                MaxWidth = 150,
                                DefaultValue = column.ColumnDefault,
                            });

И блок событий

private void dataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
    DataGridColumn column = e.Column;
    IComparer comparer = null;

    if (e.Column.SortMemberPath != "id") return;

    e.Handled = true;

    ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) 
        ? ListSortDirection.Ascending : ListSortDirection.Descending;

    column.SortDirection = direction;

    //    Error --> 
    ListCollectionView lcv = new ListCollectionView((IList)CollectionViewSource
        .GetDefaultView(dataGrid.ItemsSource));

    comparer = new SortNumerical(direction);

    lcv.CustomSort = comparer;
}

Точное сообщение об ошибке:

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Data.BindingListCollectionView' to type 'System.Collections.IList'.'

1 Ответ

0 голосов
/ 31 октября 2019

Нашел решение, которое работает.

Изменение типа ItemsSource на ObservableCollection<ExpandoObject> позволило мне динамически создавать классы в соответствии с загруженным файлом XML (спасибо C # 6).

Тогда я мог бынапрямую использовать ListCollectionView lcv = new ListCollectionView(xmlData.ItemsSource as IList);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...