I am trying to format a textblock which is bound to a TimeSpan
property. It works if the property is of type DateTime
but it fails if it is a TimeSpan
. I can get it done using a converter. But I am trying to find out if there is any alternatives.
Sample Code:
public TimeSpan MyTime { get; set; } public Window2() { InitializeComponent(); MyTime = DateTime.Now.TimeOfDay; DataContext = this; }
Xaml
<TextBlock Text="{Binding MyTime,StringFormat=HH:mm}"/>
I am expecting the textblock to show only hours and mintes. But it is showing as:
19:10:46.8048860
"c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.
You can format a TimeSpan in the hh: mm: ss format in C#.
The format string is intended to work on a DateTime
, not a TimeSpan
.
You could change your code to work with DateTime.Now
instead. Your xaml is fine:
<TextBlock Text="{Binding MyTime,StringFormat=HH:mm}"/>
Update
And from .Net 4 format a TimeSpan
as follows:
<TextBlock Text="{Binding MyTime,StringFormat=hh\\:mm}"/>
In .NET 3.5 you could use a MultiBinding instead
<TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0}:{1}"> <Binding Path="MyTime.Hours"/> <Binding Path="MyTime.Minutes"/> </MultiBinding> </TextBlock.Text> </TextBlock>
Update
To answer the comments.
To make sure you output 2 digits even if hours or minutes is 0-9 you can use {0:00} instead of {0}. This will make sure the output for the time 12:01 is 12:01 instead of 12:1.
If you want to output 01:01 as 1:01 use StringFormat="{}{0}:{1:00}"
And Conditional formatting can be used to remove the negative sign for minutes. Instead of {1:00} we can use {1:00;00}
<TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0:00}:{1:00;00}"> <Binding Path="MyTime.Hours" /> <Binding Path="MyTime.Minutes" /> </MultiBinding> </TextBlock.Text> </TextBlock>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With