StringFormat for binding TimeSpan in XAML does not work

c#, wpf, xaml

Solution

You can get that output by using this `StringFormat`:

<TextBlock Text="{Binding Time, StringFormat={}{0:hh}:{0:mm}, FallbackValue=00:00}" />

UPDATE >>>

The first point that I'd like to make is that `hh` will display hours in a 12 hour format and you should use `HH` if you want 24 hour format.

The second point that I'd like to make is that you are clearly confused as to what you are doing in your application. The time value that you are seeing with the seconds value is not coming from this `TextBlock` and probably not coming from your one either. I think that you need to take a good look at your code... you must have another `TextBlock` or something.

Problem

I have a TimeSpan variable called Time which I managed to successfully bind in XAML. Here's the code that I have: ``` ... <TextBlock Grid.Column="2" Text="{Binding Time, StringFormat='{}{0:hh:mm}'}" /> ... ``` The values are now displayed properly, however, the format is still hh:mm:ss. I'm trying to get rid of the seconds and display only the hours and the minutes but for some reason the changes that I make to the StringFormat are not accounted for and I always get the same hh:mm:ss format. Can you please advise? Thank you! EDIT: Judging by the comments below it seems that the Time that I have binded is not in TimeSpan format as the StringFormat seems to be correct but the displayed value is wrong. The Time variable is defined as follows in a custom class Record: ``` private TimeSpan time; public TimeSpan Time { get { return time; } set { time = value; } } ``` In my code I have an observable collection defined: ``` ObservableCollection<Record> records = new ObservableCollection<Record>(); ``` The collection is the populated an then I have: ``` listBoxRecords.ItemsSource = this.records; ``` Here's the full XAML, keeping in mind that the rest of the fields are correctly populated, only the TimeSpan is giving me troubles: ``` <ListBox Margin="0,44,0,58" Name="listBoxRecords" ItemsSource="{Binding records}"> <ListBox.ItemTemplate> <DataTemplate> <Grid Margin="4"> <Grid.ColumnDefinitions> <ColumnDefinition Width="120" /> <ColumnDefinition Width="85" /> <ColumnDefinition Width="55" /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding Date, StringFormat='{}{0:dd-MM-yyyy HH:mm}'}" /> <TextBlock Grid.Column="1" Text="{Binding Type }" /> <TextBlock Grid.Column="2" Text="{Binding Time, StringFormat='{}{0:hh\\:mm}'}" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ```

Original source

Related problems