Customize format of DateTime string in WPF and WinForm data binding
Drag-and-drop data binding helps you build business applications very easily, however sometimes you still need to customize the layout or format after data binding is set. For example, I built a simple application to display all the Customers, and for each Customer, the related Orders are loaded into a DataGrid control:
Of course the data in Birthday field is fake :) and of course I don’t want to show the time part 12:00:00 AM in the text. To customize the string format, first let’s go to the XAML file and locate the TextBlock which binds to Birthday:
<TextBlock Grid.Column="1" Grid.Row="3" Height="21" HorizontalAlignment="Left" Margin="3" Name="birthdayTextBlock" Text="{Binding Path=Birthday}" VerticalAlignment="Center" Width="120" />
You could write a converter to convert the string. Another simpler way is to insert a StringFormat property to the Text Binding and set it to only display the Date 1/1/2222:
Text="{Binding Path=Birthday, StringFormat=d}"
Similarly, if you set StringFormat to the “Order Date” and “Preferred Delivery Time” column:
…
<TextBlock Text="{Binding Path=OrderDate, StringFormat={}{0:dddd MMMM dd}}" />
…
<TextBlock Text="{Binding Path=DeliveryDate, StringFormat=t}" />
…
StringFormat={}{0:dddd MMMM dd} it will display the DateTime in your specified format; StringFormat=t will only display short time. Now the form looks like this:
Now you might ask, how about WinForms? It is just as easy.
On the left is the WinForm Designer surface. Set focus on the DateTimePicker control and find Format property in Properties window. Change the Format to Short so that Birthday TextBlock will only display the Date:
To set OrderDate column and PreferredDeliveryDate column to display in the format as in the WPF example above, click on the DataGridView control and click on the little smarttag button to open DataGridView Tasks:
Select Edit Columns to invoke Edit Columns dialog, and in Bound Column Properties, select DefaultCellStyle to launch CellStyle Builder:
There are some other customizations in this dialog, now let’s just focus on the Format. You could input Format like “dddd MM dd”, or launch Format String Dialog to set the string format. After setting format for both OrderDate column and PreferredDeliveryTime column, the final windows form is:
Well, isn’t it simple to change string format in data binding for both WPF and WinForm? To learn more about formatting (not only formatting DateTime string), please see: https://msdn.microsoft.com/en-us/library/fbxft59x.aspx
Cheers!
Comments
Anonymous
July 07, 2009
Nice post comparing the two techniques! But with WPF you still may want to write your own converter so that you can control the user input as well. http://blogs.msdn.com/bethmassi/archive/2008/12/12/formatting-data-in-wpf-controls.aspx Thanks Yang!Anonymous
June 17, 2012
Thanks for that couldn't figure out how to format the date in a chart binding until I found this!