WPF Datagrid сортирующий на столбце связывают с XML, содержащим числа

Я связываю свой WPF Datagrid с исходным кодом XML. У меня есть a DataGridTextColumn столбец, представляющий идентификатор моего объекта. Когда я сортирую на том столбце, он дает мне, например: 1, 12, 13, 2, 3, 31, 4.

Я, очевидно, хотел бы отсортировать его как 1, 2, 3, 4, 12, 13, 31.

Существует ли способ указать, что я хочу отсортировать столбец на основе целочисленного представления строки?

Спасибо.

1
задан JohnB 19 January 2011 в 18:05
поделиться

1 ответ

Вам придется делать сортировку самостоятельно. Вы можете использовать linq для простой сортировки xml. Приведенный ниже пример сортирует числа так, как вы ожидаете при нажатии на заголовки. Я реализовал сортировку только по возрастанию.

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"
    Height="300" Width="300">
    <StackPanel>
        <Controls:DataGrid 
            ItemsSource="{Binding Path=Trades}"
            Sorting="OnSorting">
            <Controls:DataGrid.Columns>
                <Controls:DataGridTextColumn Header="Side" Binding="{Binding Path=Attribute[Side].Value}" />
                <Controls:DataGridTextColumn Header="Price" Binding="{Binding Path=Attribute[Price].Value}" />
                <Controls:DataGridTextColumn Header="Volume" Binding="{Binding Path=Attribute[Volume].Value}" />
            </Controls:DataGrid.Columns>
        </Controls:DataGrid>
    </StackPanel>
</Window>

Code behind:

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Xml.Linq;
using Microsoft.Windows.Controls;

namespace DataGridDemo
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            DataContext = new VM();
        }

        private void OnSorting(object sender, DataGridSortingEventArgs e)
        {
            e.Handled = true;

            (DataContext as VM).SortCol = e.Column.Header as string;
        }
    }

    public class VM : INotifyPropertyChanged
    {
        public VM()
        {
            _data = 
                new XElement("Trades",
                             new XElement("Trade", new XAttribute("Side", "Buy"), new XAttribute("Price", "3.23"), new XAttribute("Volume", "100")),
                             new XElement("Trade", new XAttribute("Side", "Sell"), new XAttribute("Price", "13.12"), new XAttribute("Volume", "200")),
                             new XElement("Trade", new XAttribute("Side", "Buy"), new XAttribute("Price", "04.1"), new XAttribute("Volume", "15")),
                             new XElement("Trade", new XAttribute("Side", "Buy"), new XAttribute("Price", "30.78"), new XAttribute("Volume", "120")));

            SortCol = "Price";
        }

        private string _sortCol;
        public string SortCol
        {
            get { return _sortCol; }
            set
            {
                _sortCol = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(""));
                }
            }
        }

        public IEnumerable<XElement> Trades
        {
            get
            {
                if (SortCol == "Side")
                {
                    return from trade in _data.Elements("Trade")
                        orderby (string)trade.Attribute(SortCol)
                        select trade;
                }

                return
                    from trade in _data.Elements("Trade")
                    orderby (double)trade.Attribute(SortCol)
                    select trade;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private XElement _data;
    }
}
1
ответ дан 2 September 2019 в 23:13
поделиться
Другие вопросы по тегам:

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