Tengo un DataGrid en mi aplicación WPF y su propiedad ItemsSource está configurada en un DataTable. Pero el problema es que la columna de fecha muestra la fecha en el formato "mm/dd/aaaa" y quiere en el formato de fecha "dd/mm/aaaa". Entonces, ¿cuál será la forma más óptima de lograrlo? Como estoy consultando la tabla desde la base de datos de MS Access, siempre recibo la fecha en formato inglés
Veo dos formas sencillas de establecer la representación de fecha deseada: establecer la referencia cultural (idioma) requerida en DataGrid y la generación automática controlada de columnas.
En la segunda opción, personalizas las columnas que necesitas en el evento AutoGeneratingColumn.
Ejemplo:
using System; using System.Data; namespace DateColumnFormat { public class DatesSource { public DataTable Table { get; } = new DataTable(); private static readonly Random random = new Random(); private static readonly DateTime begin = new DateTime(1900, 1, 1); private static readonly DateTime end = DateTime.Today; private static readonly double interval = (end - begin).TotalSeconds; public DatesSource() { // Creating one column and ten rows with random dates Table.Columns.Add(new DataColumn("Dates", typeof(DateTime))); for (int i = 0; i < 10; i++) { DataRow newRow = Table.NewRow(); newRow[0] = begin.AddSeconds(random.NextDouble() * interval); Table.Rows.Add(newRow); } } } }Vista:
<Window x:Class="DateColumnFormat.FormatTestWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DateColumnFormat" mc:Ignorable="d" Title="FormatTestWindow" Height="300" Width="500"> <FrameworkElement.DataContext> <local:DatesSource/> </FrameworkElement.DataContext> <UniformGrid Rows="1"> <DataGrid ItemsSource="{Binding Table}"/> <DataGrid ItemsSource="{Binding Table}" Language="ru"/> <DataGrid ItemsSource="{Binding Table}" AutoGeneratingColumn="OnAutoGeneratingColumn"/> </UniformGrid> <x:Code> <![CDATA[ private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { if (e.PropertyName == "Dates") { var column = (DataGridTextColumn)e.Column; var binding = (Binding)column.Binding; binding.StringFormat = "dd-MMMM-yyyy"; binding.ConverterCulture = System.Globalization.CultureInfo.GetCultureInfo("de-De"); } } ]]> </x:Code> </Window>