6

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>
mmvsbg
  • 3,570
  • 17
  • 52
  • 73
  • 1
    The problem has not been solved yet or I would have gladly accepted an answer. – mmvsbg Jul 18 '14 at 12:39
  • And when you try my answer, what happens (bearing in mind my comment that what you saw was *not* coming from my `StringFormat`)? Try it in a new project and you will see that it works just fine. – Sheridan Jul 18 '14 at 13:31
  • http://stackoverflow.com/questions/4563081/how-to-format-timespan-in-xaml – Herman Cordes Oct 29 '14 at 09:29

6 Answers6

10

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.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • 1
    That prints the same string twice, something like 12:32:0012:32:00. – mmvsbg Nov 25 '13 at 16:00
  • You seem to be mixing up this `StringFormat` with another... for example, there are no seconds in this `StringFormat`, so it will *never* display seconds like your example in your comment. In my application, it displays exactly as expected. – Sheridan Nov 25 '13 at 16:08
  • Unfortunately I can confirm it does not work this way and I have the same result as 'mmvsbg' does. Currently I'm on a net35 project, maybe it does work the way you suggested on a net40 or net45 project. – Herman Cordes Oct 29 '14 at 09:24
  • Also see for a working solution on net35: http://stackoverflow.com/questions/4563081/how-to-format-timespan-in-xaml – Herman Cordes Oct 29 '14 at 09:30
  • @HermanCordes, you are also mistaken. I have just tested this `StringFormat` in both .NET 3.5 *and* .NET 3.5 Client Profile and it works exactly as expected. Try again yourself *in a new Project* and you'll see that it does 'exactly what it says on the tin'. – Sheridan Oct 29 '14 at 10:06
  • @Sheridan, I've just tried myself and somehow it doesn't do what it says on the tin. I've created three solutions the same way: 1st on net35, 2nd on net40, 3rd on net45. All with just the one line from your answer on MainWindow.xaml and in MainWindow.xaml.cs an assignment 'DataContext = this' and one property 'public TimeSpan Time { get { return new TimeSpan(11, 10, 9); } }'. Only the net35 results in '11:10:09:11:10:09', please see screenshot. http://pasteboard.s3.amazonaws.com/images/1k1BGozI.png – Herman Cordes Oct 30 '14 at 08:52
  • 2
    @Sheridan Fails completely for me in WPF with .NET 4.5, in a new project. "'StringFormat' converter failed to convert value" – 15ee8f99-57ff-4f92-890c-b56153 Jan 07 '16 at 20:59
  • 3
  • Thanks for providing that information. I've not had that problem personally, but it's just as well that there are several different ways to achieve the same result. – Sheridan Jan 07 '16 at 22:39
8

Try escaping : by changing your StringFormat to something like:

StringFormat='{}{0:hh\\:mm}'
dkozl
  • 32,814
  • 8
  • 87
  • 89
  • I tried but still no success. – mmvsbg Nov 25 '13 at 15:53
  • I have tried my code on a `TimeSpan` property and it worked fine but what is really strange is that in your case, you say, it ignores `StringFormat` all together and shows default format whilst in my case your code showed nothing. Are you 100% sure that you bind to `TimeSpan Time {...}` property that you think you bind to. – dkozl Nov 25 '13 at 15:59
  • In fact I've seen your solution around in the net and I was surprised it didn't work. I have an ObservableCollection of type which has a property Time of type TimeSpan. The collection called 'records' is set as the ItemsSource of a ListBox that displays it and the ListBox itself has a ItemsSource="{Binding records}. I'm assuming it all works fine as the rest of the fields in MyClass are properly displayed in the ListBox and the TimeSpan values themselves are correct - except that I want to hide the seconds as there's no need to show them on the UI. – mmvsbg Nov 25 '13 at 16:05
  • 2
    Can you update your question with definition of `MyClass`, mainly how `Time` property is defined? Judging by your comment to other answer it looks as `StringFormat` is ignored because it's not `TimeSpan`. Besides default `TimeSpan` format would be `hh:mm:ss.fffffff` and you're missing miliseconds part – dkozl Nov 25 '13 at 16:13
  • @mmvsbg, I've seen your update and all seems in order. I cannot see anything obvious. I've also checked [MSDN](http://msdn.microsoft.com/en-us/library/1ecy8h51(v=vs.110).aspx) and `.fffffff` is actually optional and may not be included if you have full seconds so what you're getting may as well be default format for `TimeSpan` – dkozl Nov 25 '13 at 17:29
  • Thanks for your time! I'll keep on trying to solve this mystery as it all seems fine to me as well and I'll post another update if I find something. – mmvsbg Nov 25 '13 at 17:32
  • Ran into exactly the same issue in another piece of software, completely different setting and still no solution... – mmvsbg Dec 03 '13 at 16:34
6

None of the proposed answers worked for me, they all produces binding errors. I ended up making a sample app to test every possible string format found on MSDN: Custom TimeSpan Format Strings

I found from this testing that only the TimeSpan parts which start with % (like %d for Days) worked in WPF StringFormat property.

Try this, it worked for me:

<TextBlock
    Text="{Binding Path=Time,
        StringFormat={}{0:%d} days {0:%h} hours {0:%m} minutes,
        FallbackValue=0 days 0 hours 0 minutes}" />
turkinator
  • 905
  • 9
  • 25
3

from .Net 4 for timespan you can use

    <TextBlock Grid.Column="2" Text="{Binding Time, StringFormat=hh\\:mm\\:ss}" />

as for tim-lloyd answer in How to format TimeSpan in XAML

Mark as answer if it worked.

Regards

3

Searched numerous threads with this problem i found that: As of July 4th, 2019 this works for me in XAML in Xamarin forms:

Text="{Binding myTimeSpan, StringFormat=\{0:h\\:mm\\:ss\}, FallbackValue=00:00:00}

It displays time in hour, minutes, seconds:

1 hour 23 minutes and 9 seconds = 1:23:09

Richard Suarez
  • 109
  • 1
  • 10
2

For those interested in a programmatic approach, this worked for me:

        {
            DataGridTextColumn dgtc = new DataGridTextColumn();
            dgtc.Header = "End Time";
            dgtc.Binding = new Binding("EndTime");
            dgtc.Binding.StringFormat = "{0:hh}:{0:mm}";
            ScheduleGrid.Columns.Add(dgtc);
        }
BitsAndBytes
  • 815
  • 1
  • 9
  • 13