简体   繁体   中英

DateTime format changing when used as DataGrid ItemSource

I have a class which has two properties, a string and DateTime. The DateTime property is assigned a value in the constructor:

this._lastCheckIn = DateTime.Parse(lastCheckIn.ToString("dd/MM/yyyy HH:mm"));

Where the lastCheckIn variable is passed to the constructor.

I can see at runtime that the object is being created with the DateTime in the format I have specified here but when it is shown on the DataGrid the format reverts back to US.

Previously I had a string as opposed to DateTime in my object which showed the format correctly but didn't sort properly when I sorted ascending or descending in the datagrid. 25/1/2015 would show higher than 24/2/2015.

Not too sure where I'm going wrong here, any help would be greatly appreciated!

You can choose the string format in the column binding

<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding MyDate, StringFormat=\{0:dd.MM.yy \}}" />
    </DataGrid.Columns>
</DataGrid>

The date is displayed using the culture of the system the application is running on. You can either change the date time format of the datagrid itself or apply it to the entire application at start up.

var culture = Thread.CurrentThread.CurrentCulture;
culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy HH:mm";

var uiCulture = Thread.CurrentThread.CurrentUICulture;
uiCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy HH:mm";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM