Предварительная сортировка DataGrid в WPF

Вы можете использовать объект FormData , чтобы получить значения вашей формы, а затем добавить версию blob вашего холста в FormData.

Этот blob будет рассматриваться как файл сервером.

К сожалению, все браузеры по-прежнему не поддерживают собственный метод canvas.toBlob() и даже стоит, все реализации не совпадают. Все основные браузеры теперь поддерживают метод toBlob, и вы можете найти polyfill для mdn для старых браузеров.

// the function to create and send our FormData
var send = function(form, url, canvas, filename, type, quality, callback) {

  canvas.toBlob(function(blob){
    var formData = form ? new FormData(form) : new FormData();
    formData.append('file', blob, filename);

    var xhr = new XMLHttpRequest();
    xhr.onload = callback;
    xhr.open('POST', url);
    xhr.send(formData);

    }, type, quality);
};

// How to use it //

var form = document.querySelector('form'),   // the form to construct the FormData, can be null or undefined to send only the image
  url = 'http://example.com/upload.php',     // required, the url where we'll send it
  canvas = document.querySelector('canvas'), // required, the canvas to send
  filename = (new Date()).getTime() + '.jpg',// required, a filename
  type = 'image/jpeg',                       // optional, the algorithm to encode the canvas. If omitted defaults to 'image/png'
  quality = .5,                              // optional, if the type is set to jpeg, 0-1 parameter that sets the quality of the encoding
  callback = function(e) {console.log(this.response);}; // optional, a callback once the xhr finished

send(form, url, canvas, filename, type, quality, callback);

Сторона PHP тогда будет:

if ( isset( $_FILES["file"] ) ){
    $dir = 'some/dir/';
    $blob = file_get_contents($_FILES["file"]['tmp_name']);
    file_put_contents($dir.$_FILES["file"]["name"], $blob);
    }

26
задан devuxer 26 October 2009 в 20:45
поделиться

5 ответов

Предполагая, что вы говорите об элементе управления WPG Toolkit DataGrid, вам нужно только установить свойство CanUserSortColumns в значение true, а затем установить свойство SortMemberPath каждого DataGridColumn в DataGrid.

Что касается первоначальной сортировки коллекции, вы должны использовать CollectionViewSource и установить для нее сортировку, а затем назначить ее в качестве ItemsSource вашей DataGrid. Если вы делаете это в XAML, то это будет так просто:

<Window.Resources>
    <CollectionViewSource x:Key="MyItemsViewSource" Source="{Binding MyItems}">
        <CollectionViewSource.SortDescriptions>
           <scm:SortDescription PropertyName="MyPropertyName"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>

<DataGrid ItemsSource="{StaticResource MyItemsViewSource}">

</DataGrid>

ПРИМЕЧАНИЕ: префикс пространства имен «scm» сопоставляется с System.ComponentModel, где живет класс SortDescription.

xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

РЕДАКТИРОВАТЬ: Я думаю, что достаточное количество людей получило помощь от этого поста, что этот голосующий комментарий должен быть включен в этот ответ:

Я должен был использовать это, чтобы получить его работа:

<DataGrid ItemsSource="{Binding Source={StaticResource MyItemsViewSource}}">
44
ответ дан DLeh 15 October 2019 в 07:26
поделиться

Я знаю, что это старая публикация, но в дополнение к ответу Дрю Марша и в ответ на проблему DanM с появлением стрелок заголовка столбца ... Вам необходимо добавить свойство SortDirection в DataGridColumn:

<DataGridTextColumn Header="Name" Binding="{Binding Name}" SortDirection="Ascending" />

Я опубликовал вопрос по этому поводу и нашел ответ через несколько дней:

Стрелки ColumnHeader не отражаются при сортировке DataGrid в XAML

18
ответ дан Community 15 October 2019 в 07:26
поделиться

Когда вы видите исключение ItemsSource doesn't support CollectionViewSource, вы можете отсортировать коллекцию по Linq, прежде чем передать ее в DataGrid:

ObservableCollection<MyDataClass> myCollection = new ObservableCollection<MyDataClass>();
dataGrid.ItemsSource = from item in myCollection orderby item select item;

Необходимо реализовать интерфейс IComparable для MyDataClass:

public class MyDataClass : IComparable<MyDataClass> {
    public int CompareTo(Classified other) {
        return other.Value.CompareTo(this.Value); // DESC
        return this.Value.CompareTo(other.Value); // ASC
    }
}
2
ответ дан Václav Dajbych 15 October 2019 в 07:26
поделиться

Это работает для меня.

ListSortDirection sortDirection;
int selectedColumnIndex;
private void customerDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
    selectedColumnIndex = e.Column.DisplayIndex;
    sortDirection = (e.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending: ListSortDirection.Ascending);
}

private void applySortDescriptions(ListSortDirection listSortDirection)
{
    //Clear current sort descriptions 
    customerDataGrid.Items.SortDescriptions.Clear();

    //Get property name to apply sort based on desired column 
    string propertyName = customerDataGrid.Columns[selectedColumnIndex].SortMemberPath;

    //Add the new sort description 
    customerDataGrid.Items.SortDescriptions.Add(new SortDescription(propertyName, listSortDirection));

    //apply sort 
    applySortDirection(listSortDirection);

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

private void applySortDirection(ListSortDirection listSortDirection)
{
    customerDataGrid.Columns[selectedColumnIndex].SortDirection = listSortDirection;
}
0
ответ дан Pramod Pawar 15 October 2019 в 07:26
поделиться

Когда вы видите, что ItemsSource не поддерживает исключение CollectionViewSource, вы можете установить DataContext для DataGrid как 'MyItemsViewSource' и ItemsSource как {Binding} следующим образом:

<DataGrid DataContext="{StaticResource MyItemsViewSource}" ItemsSource="{Binding}">
</DataGrid>
4
ответ дан 28 November 2019 в 06:31
поделиться
Другие вопросы по тегам:

Похожие вопросы: