Using XAML rather than code is a far easier way of working with controls including the
DataGrid
.
Here is an example of an answer to an older question with a similar question. Create a new project called
WpfDataGridDateColumnFormatting
and drop this code in:
1. Create a new Model called
Widget
to hold the data:
public class Widget
{
public string? Name { get; set; }
public DateTime? Date { get; set; }
public int Quantity { get; set; } = 0;
}
2. Add the following code to the
MainWindow
code-behind:
using System;
using System.Collections.ObjectModel;
using System.Windows;
public partial class MainWindow : Window
{
private Random random = new();
public ObservableCollection<Widget> Widgets { get; set; } = new();
public MainWindow()
{
CreateWidgets();
InitializeComponent();
}
private void CreateWidgets()
{
for (int i = 0; i < 10; i++)
{
Widgets.Add(new()
{
Name = $"Widget {i}",
Date = DateTime.Now.AddDays(random.NextDouble() * 5),
Quantity = random.Next(0, 100)
});
}
}
}
3. Now the
MainWindow
XAML:
<Window x:Class="WpfDataGridDateColumnFormatting.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="Window"
Title="MainWindow" Height="450" Width="800">
<DataGrid DataContext="{Binding ElementName=Window}"
ItemsSource="{Binding Widgets}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Name}" />
<DataGridTextColumn Header="Date"
Binding="{Binding Date,
StringFormat={}{0:dd.MM.yy}}" />
<DataGridTextColumn Header="Quantity"
Binding="{Binding Quantity,
StringFormat={}{0:#,##0.00}}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Right" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
Now, if you followed the instructions above, and run the app, you will see the last two columns with custom formatting, and the last with number formatting.
As you can see, we are applying the formatting directly on the data binding:
Binding="{Binding Quantity, StringFormat={}{0:#,##0.00}}">
The
StringFormat
property in the data binding uses the same formatting options as
String.Format
. (ref:
Standard numeric format strings[
^])
A great tutorial website for WPF:
The complete WPF tutorial - WPF tutorial[
^]
Hope this helps!