简体   繁体   English

在wpf datagrid中的字符串属性中强制日期排序

[英]Force date sorting in string properties in wpf datagrid

I have a datagrid, that has all columns binded to string properties. 我有一个datagrid,它具有将所有列绑定到字符串属性的功能。

I create these columns in runtime, so I need to make the bind programmatically: 我在运行时创建这些列,因此需要以编程方式进行绑定:

var c = new DataGridTextColumn();
c.Header = myProperty;
c.Binding = new Binding(myProperty);
if (thisColumnsIsDate())
    c.Binding.StringFormat = "{0:dd/MM/yyyy}";
myGrid.Columns.Add(c);

The problem is that the grid sorts these date columns like string , not DateTime . 问题是网格对这些日期列进行排序,例如string ,而不是DateTime

This is the grid definition: 这是网格定义:

<DataGrid
            Grid.Row="1"
            Margin="2"
            Name="myGrid"
            AutoGenerateColumns="False"
            IsEnabled="True"
            IsReadOnly="True"
            ItemsSource="{Binding Path=Rows}"
            SelectedItem="{Binding Path=SelectedRow}"
            HorizontalGridLinesBrush="Transparent" VerticalGridLinesBrush="Transparent" AlternatingRowBackground="WhiteSmoke"
            PreviewKeyDown="gridResult_OnKeyDown">

What´s missing? 缺少了什么?

This should correct the sorting for Date columns: 这应该更正“日期”列的排序:

c.SortMemberPath = myProperty;

But if your property is a string you need to convert it to a DateTime first: 但是,如果您的属性是字符串,则需要先将其转换为DateTime:

var c = new DataGridTextColumn();
c.Header = myProperty;

if (thisColumnsIsDate())
{
    myDateTimeProperty = DateTime.Parse(myProperty);
    c.Binding = new Binding(myDateTimeProperty);
    c.Binding.StringFormat = "{0:dd/MM/yyyy}";
    c.SortMemberPath = myDateTimeProperty;
}
else
{
    c.Binding = new Binding(myProperty);
    c.Binding.StringFormat = "{0:dd/MM/yyyy}";
    c.SortMemberPath = myProperty;
}
myGrid.Columns.Add(c);

Moreover, you can implement your own comparer: How can I apply a custom sort rule to a WPF DataGrid? 此外,您可以实现自己的比较器: 如何将自定义排序规则应用于WPF DataGrid?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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