StringFormat of Datetime object in binding gives back 0 for hour and minute

北战南征 提交于 2019-12-20 06:12:27

问题


I create a Datetime object with Datetime.Now and I have this as a property of a class.

When I bind this to a grid view:

<GridViewColumn Header="Date" Width="120" DisplayMemberBinding="{Binding transaction_date1, StringFormat=HH:mm}" />

The result is always 00:00.

When I debug the code I see that the hour, minute etc. properties of the Datetime object contain non-zero values. I think that the StringFormat in this case gets the hour and minute from the Date object within the Datetime object that has the correct dates but always has 12:00:00 AM as hour.

Is there any way to go past it and display the right hour and minute in my window?

Thank you in advance!


回答1:


Change it to this:

<GridViewColumn Header="Date" Width="120" DisplayMemberBinding="{Binding transaction_date1, StringFormat='{}{0:HH:mm}'}" />

If you want to use StringFormat with custom formatting, then you have to use this method where you provide the param index in the format string. It is equivalent to:

string.Format("{0:HH:mm}", transaction_date1);

The two curly braces at the start {} are an instruction to the XAML parser to ignore further curly braces found in the string. So you could use your date value multiple times in one binding statement:

DisplayMemberBinding="{Binding transaction_date1, StringFormat=`{} Your date-time is {0:dd/mm/yy} at approx. {0:HH} hours and {0:mm} minutes`}"


来源:https://stackoverflow.com/questions/33445385/stringformat-of-datetime-object-in-binding-gives-back-0-for-hour-and-minute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!