String format using UWP and x:Bind
Use a StringFormatConverter
(check if you maybe use some library, which already includes it, e.g. the UWP Toolkit (thanks, @maxp) or the older Cimbalino Toolkit):
public class StringFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
if (parameter == null)
return value;
return string.Format((string)parameter, value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
add it to your page resource
<Page.Resources>
<converters:StringFormatConverter x:Key="StringFormatConverter" />
</Page.Resources>
and use it like this
<TextBlock Text="{x:Bind Text, Converter={StaticResource StringFormatConverter}, ConverterParameter='{}{0:dd/MM/yyy HH\\\\:mm (ddd)}'}" />
you can use
{x:Bind ViewModel.DateTimeProperty.ToString("....")}
Function binding is much better approach than classic Converter:
<TextBlock Text="{x:Bind DateTimeToString(MyDateTime,'dd/MM/yyy HH\\\\:mm (ddd)')}" />
Code behind (it could be placed in separate class):
//"Converter"
public string DateTimeToString(DateTime dateTime, string format) => dateTime.ToString(format);
public DateTime MyDateTime { get; set; } = DateTime.Now;
Why is it better than classic converter?
- Shorter -> no boil plait code
- Strongly typed -> Detects exceptions in build time.