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
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}"/>