WPF: Date conversion with IValueConverter

This entry is part 45 of 54 in the series Learn WPF

Each time when we retrieve a date from the database, it will usually be in a format that include the time.

Here, we will use IValueConverter to convert a date into the format dd-MMM-yyyy.  For example, 20-Apr-2014.

<Window x:Class="ConverterName.ValueConverter"
        Title="IvalueConverterDemo" Height="350" Width="525">
        <local:DateConverter x:Key="dateconverter" />
        <DataGrid x:Name="batch" AutoGenerateColumns="False" >
                <DataGridTextColumn Header="Batch ID" Binding="{Binding BatchID }" />
                <DataGridTextColumn Header="Batch Name" Binding="{Binding BatchName }"/>
                <DataGridTextColumn Header="Batch Start Date" Binding="{Binding StartDate, Converter={StaticResource dateconverter}}"/>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ConverterName
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public class Batches
        public int BatchID { get; set; }
        public string BatchName { get; set; }
        public DateTime StartDate { get; set; }

    public class DateConverter : IValueConverter
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            if (value != null)
                DateTime dt = (DateTime)value;
                return dt.ToString("dd-MMM-yyyy");
            return string.Empty;

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            throw new Exception();

    public partial class ValueConverter : Window
        List<Batches> batchList = new List<Batches>();

        public ValueConverter()

            batchList.Add(new Batches { BatchID = 1, BatchName = "Winter", StartDate = Convert.ToDateTime("2011-09-01 08:58:28.410") });
            batchList.Add(new Batches { BatchID = 2, BatchName = "Summer", StartDate = Convert.ToDateTime("2012-02-01 08:58:28.410") });
            batchList.Add(new Batches { BatchID = 3, BatchName = "Rainy", StartDate = Convert.ToDateTime("2012-07-01 08:58:28.410") });

            batch.ItemsSource = batchList;

The Convert.ToDateTime in line 46 will take in a string put them in date-time format recognisable by C# code.

It is only with this conversion that we can cast it to DateTime object in line 26.



Series Navigation<< WPF: A simple IValueConverter implementation
WPF: Listview with IValueConverter >>

Leave a comment

Leave a Reply