StringFormat on Binding
The best and the easiest way would be to use a converter to which you pass the Date and get the formatted string back. In e.g. MyNamespace.Converters
namespace:
public class DateFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
DateTime dt = DateTime.Parse(value.ToString());
return dt.ToString("dd/MM/yyyy");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
And in your xaml just reference the converter and add the following converter:
xmlns:conv="using:MyNamespace.Converters"
in your xaml page and in page.resources add this
<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/>
<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/>
There is no property named StringFormat
in Binding class. You can use Converter and ConverterParameter to do this. You can refer to Formatting or converting data values for display.
For example here, I bind the date of a DatePicker
to the text of a TextBlock
.
XAML:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.Resources>
<local:DateFormatter x:Key="DateConverter"/>
</Grid.Resources>
<DatePicker Name="ConverterParmeterCalendarViewDayItem"></DatePicker>
<TextBlock Height="100" VerticalAlignment="Top" Text="{Binding ElementName=ConverterParmeterCalendarViewDayItem, Path=Date, Converter={StaticResource DateConverter},ConverterParameter=\{0:dd/MM/yyyy\}}" />
</Grid>
code behind, the DateFormatter class:
public class DateFormatter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var a = language;
// Retrieve the format string and use it to format the value.
string formatString = parameter as string;
if (!string.IsNullOrEmpty(formatString))
{
return string.Format(formatString, value);
}
return value.ToString();
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return DependencyProperty.UnsetValue;
}
}