How to properly format DateTime with annotations in WPF MVVM application

Francesco Paolo La Gamba 21 Reputation points
2023-07-03T13:40:57.69+00:00

Hi Community,

I have a seemingly trivial problem: I'm trying Community.MVVM.Toolkit and I've created a class that exposes some properties among which there is a DateTime type (BirthDate).

Well, despite several searches on the web, I can not get the formatting of the date in the my required format using the Annotations.

The format I would like to obtain is of type "yyyy-MM-dd" without the time.

I specified it in the property annotations using the following annotation:

      [ObservableProperty]
      [NotifyDataErrorInfo]
      [Required]
      [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
      public DateTime?  _birthDate;

The XAML definition:

<TextBox x:Name="txtBirthDate" Width ="200"   Text="{Binding Path=BirthDate,  UpdateSourceTrigger=LostFocus,      ValidatesOnDataErrors=true}"  Margin="5" />

Now if I enter the date 30/11/2022 ( November 30, 2022 in italian format)

the result in the TextBox is "11/30/2022 12:00:00 AM"

The specified format is absolutely not taken into consideration.

How can I solve the problem ?

Maybe I could add a further property that transforms the date into a string... but in this way I lose the advantages of the toolkit and I don't want to do it, if possible.

Best regards

Francesco Paolo La Gamba

Developer technologies Windows Presentation Foundation
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.