How do you format a TimeSpan
in XAML with a custom format? I want hour and minutes.
Based on the official documentation, the way to do this in C# seems like it should be:
interval.ToString(@"h\:mm");
I want to be able to format the TimeSpan
in XAML, however, from within a binding. This solution seems viable, but I wanted to create a general converter, that I could pass a format string into. My converter is as follows:
public class TimeSpanFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string result = "";
if (value == null)
{
return null;
}
if (parameter == null)
{
return value;
}
if (value is TimeSpan timeSpan)
{
try
{
result = timeSpan.ToString((string)parameter);
}
catch (Exception e)
{
result = "";
}
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
In theory, I could use this converter as follows:
<Page.Resources>
<converters:TimeSpanFormatConverter x:key="TimeSpanConverter"></converters:TimeSpanFormatConverter>
</Page.Resources>
<Grid>
<!-- Some properties omitted for brevity. -->
<ListView>
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:MyModel">
<Grid>
<!-- PROBLEM IS HERE -->
<TextBlock Text="{x:Bind Interval, Converter={StaticResource TimeSpanConverter}, ConverterParameter='h\:mm'}"></TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Note here that 'MyModel' has a property called 'Interval' that is of type 'TimeSpan'.
This does not work, however, because I need the backslash. The XAML parsing removes the backslash, thus passing in "h:mm" to the converter (which I verified through the debugger).
It also does not like two backslashes, as that throws a compiler error from the generated .g.cs file, saying "\:" is an "unrecognized escape sequence".
No variations of encoding the back slash have worked. I have tried:
h:mm
h\:mm
h\\:mm
h\\\:mm
h\:mm
h\\:mm
h\\:mm
h\\:mm
What is the magic string of letters that need to be put into the ConverterParameter
?
As an alternative, the MultiBinding solution explained here looked promising, but according to Visual Studio, MultiBinding is not supported in UWP.