C#中WPF DataGrid的变量日期格式

时间:2015-05-14 19:10:43

标签: c# wpf datagrid

我在DateTime中有一个List<>字段用作WPF ItemSource中的DataGrid,我希望根据值进行不同格式化。

如果DateTime值在DateTime.Now的一年内,我想使用'MMM dd hh:mm'作为格式,如果超过DateTime.Now的一年,我想使用'MMM dd yyyy'作为格式,如果正好是DateTime.MinValue,则希望数据网格中的单元格为空。

这是我所拥有的代码,目前仅以'MMM dd hh:mm'格式显示日期。

是否可以直接在XAML中定义此变量格式?

如果没有,我如何在DataGrid_Loaded事件中以编程方式修补格式?

Screenshot of the code's output

   public class DeadlineItem
    {
        public string Name { get; set; }
        public DateTime Deadline {get; set; }

        public DeadlineItem(string aName, DateTime aDeadline)
        {
            this.Name = aName;
            this.Deadline = aDeadline;
        }
    }

    private void DataGrid_Loaded(object sender, RoutedEventArgs e)
    {
        var items = new List<DeadlineItem>();

        items = new List<DeadlineItem>();
        items.Add(new DeadlineItem("Distant deadline", DateTime.Now.AddDays(500)));
        items.Add(new DeadlineItem("Near Deadline", DateTime.Now.AddDays(1)));
        items.Add(new DeadlineItem("No Deadline", DateTime.MinValue));
        // ... Assign ItemsSource of DataGrid.
        var grid = sender as DataGrid;
        grid.ItemsSource = items;
    }

XAML是:

<DataGrid
        AutoGenerateColumns="False"
        HorizontalAlignment="Left"
        Margin="0,0,0,0"
        VerticalAlignment="Top"
        Loaded="DataGrid_Loaded">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                    <DataGridTextColumn Header="Deadline" Binding="{Binding Deadline, StringFormat=\{0:MMM dd HH:mm\}}" />
                </DataGrid.Columns>
            </DataGrid>

1 个答案:

答案 0 :(得分:2)

正如尤金所说,你会想要使用转换器。首先,您需要添加一个实现IValueConverter的类:

public class DateTimeFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var dateValue = value as DateTime?;

        if (dateValue != null)
        {
            var diff = dateValue - DateTime.Now;

            // Greater than 1 year, format as MM/dd/yyyy
            if (diff > new TimeSpan(365, 0, 0, 0))
            {
                return dateValue.Value.ToString("MMM dd yyyy");
            }
            else if (dateValue == DateTime.MinValue)
            {
                return "";
            }
            else
            {
                return dateValue.Value.ToString("MMM dd hh:mm");
            }
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

现在,您需要在xaml文件中引用转换器。类似的东西:

<Window.Resources>
    <TestWpf:DateTimeFormatConverter x:Key="DateTimeFormatConverter"></TestWpf:DateTimeFormatConverter>
</Window.Resources>

最后,您将更改绑定以使用转换器:

<DataGrid
AutoGenerateColumns="False"
HorizontalAlignment="Left"
Margin="0,0,0,0"
VerticalAlignment="Top"
Loaded="DataGrid_Loaded">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
        <DataGridTextColumn Header="Deadline" Binding="{Binding Deadline, Converter={StaticResource DateTimeFormatConverter}}" />
    </DataGrid.Columns>
</DataGrid>

您无需担心排序,数据网格将对基础日期排序,而不是格式化字符串。