DataGrid显示错误的日期格式

本文关键字:日期 格式 错误 显示 DataGrid | 更新日期: 2023-09-27 18:27:24

我正在显示一些关于DataGrid中已经存在的案例的信息。

在我的MS Access数据库中,所有日期都以DateTime格式存储,如下所示:dd/MM/yyyy。

问题是,当程序运行时显示在DataGrid上时,格式会更改为MM/dd/yyyy。

让我迷失的是,当我在MessageBox中显示相关单元格的内容时,就在将DataTable分配给DataGrid之前,我得到了正确的格式(dd/MM/yyyy)。

我试图更改DateTimeMode,但显示的格式相同。

有人知道谁来解决这个问题吗?我给你下面的代码:

数据表温度=dt。克隆();

            temp = (from nardin in dt.AsEnumerable().Distinct()
                    where nardin["NUMERO CLIENT"].ToString() == _centerID.ToString()
                    select nardin).CopyToDataTable();


            RemoveDuplicates(temp, "NUMERO DOSSIER");

            foreach (DataRow row in temp.Rows)
            {
                MessageBox.Show(row["DATE INTERVENTION"].ToString()); //this gives me the DateTime format i'd like to display
            }
            existingCase.ItemsSource = temp.AsDataView(); //once assigned to the DataGrid the DateTime format is not the same as above

实际上,DataGrid在xaml文件中是这样声明的:

   <DataGrid  SelectionUnit="FullRow" SelectedItem="{Binding SelectedBI, Mode=TwoWay}" AutoGenerateColumns="True"   Margin="0,167,12,167" Name="existingBI"  Width="588" HorizontalAlignment="Right">
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">
                <EventSetter Event="MouseDoubleClick" Handler="resultDataGridBI_MouseDoubleClick"/>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>

我正在将DataTable与:existingCase.ItemsSource = temp.AsDataView(); 绑定

提前,谢谢!

DataGrid显示错误的日期格式

试试这个:

App.xaml文件中添加Startup事件句柄:

<Application x:Class="DataGridAddRows.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Startup="Application_Startup" ... />

App.xaml.cs中添加以下内容:

public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),
            new FrameworkPropertyMetadata(System.Windows.Markup.XmlLanguage.GetLanguage(System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag)));
    }
}            

现在,应该根据当前区域性显示日期。

Note:StringFormat仅适用于显示日期。如果要编辑具有日期的单元格,例如格式为dd/MM/yyyy的单元格,以dd/MM/yyyy的方式输入数据,则系统应为格式MM/dd/yyyy,因此错误将显示为红色Border

如果不在显示DateTime对象的DataGrid中显示列的代码,很难回答,但我假设您正在绑定该值。要在绑定上设置字符串格式,您可以执行以下操作:

<DataGrid ItemsSource="{Binding Items}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Value" Binding="{Binding Value, 
            StringFormat={}{0:dd/MM/yyyy}}" />
    </DataGrid.Columns>
</DataGrid>