StringFormat on Binding

24,528

Solution 1

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

Solution 2

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;
    }
}

Solution 3

I know this is late but I had the same question and came up with this solution. Maybe not the shortest but pure XAML.

    <TextBlock>
        <Run Text="{x:Bind Foo.StartDate.Day}"/>.<Run Text="{x:Bind Foo.StartDate.Month}"/>.<Run Text="{x:Bind Foo.StartDate.Year}"/>
    </TextBlock>

Solution 4

Since 14393, you can use functions in x:Bind.

This means you can format your date like:

Text="{x:Bind sys:String.Format('{0:dd/MM/yyyy}', ViewModel.Date)}"

Just ensure you have included a reference to the System namespace:

<Page 
     xmlns:sys="using:System"
     ...

Solution 5

why to complicate? You can use compiled data binding

{x:Bind ViewModel.PropertyWithDateTime.ToString("....")}
Share:
24,528

Related videos on Youtube

developer033
Author by

developer033

A beginner programmer

Updated on July 05, 2020

Comments

  • developer033
    developer033 almost 4 years

    View:

    <TextBlock Text="{Binding Date}"/>
    

    I want to format the Date to "dd/MM/yyyy", in other words, without the time.

    I tried it: <TextBlock Text="{Binding Date, StringFormat={}{0:dd/MM/yyyy}}"/>, but it doesn't work.

    Gives me an error: The property 'StringFormat' was not found in type 'Binding'.

  • James Croft
    James Croft over 8 years
    Came to give exactly the same answer. The best way it can be done is with a converter, as shown above, unless you change the Date to a string in code-behind and format it there instead. Info on DateTime formats
  • developer033
    developer033 over 8 years
    It doesn't work. Error: The resource "DateStringToFormatConverter" could not be resolved.
  • developer033
    developer033 over 8 years
    Unfortunately, it isn't working here..The type 'local:DateFormatter' was not found. What am I missing?
  • CodeNoob
    CodeNoob over 8 years
    You have to declare the converter in your xaml to use it
  • developer033
    developer033 over 8 years
    If you could edit your answer to a complete answer, would be great.
  • Grace Feng
    Grace Feng over 8 years
    You need to create a class named DateFormatter, please see my DateFormatter class.
  • Grace Feng
    Grace Feng over 8 years
    @developer033 Ok, please see my shared sample StringFormatInBinding.
  • developer033
    developer033 over 8 years
    @GraceFeng-MSFT I downloaded your project and put everything equal to its... Same error: "The type 'local:DateFormatter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.".
  • Grace Feng
    Grace Feng over 8 years
    ....Did you delete this xmlns:local="using:'your project'"? If not, there is some problem with the xaml designer, it may be tagged as a error, but you can still run this project and it should work fine.
  • dex3703
    dex3703 over 7 years
    @GraceFeng-MSFT - Your OneDrive link doesn't work any more. Could you update it?
  • Billy Jake O'Connor
    Billy Jake O'Connor over 7 years
    Use the parameter to pass the format string and this does the job. I wonder why they didn't implement StringFormat in UWP?
  • stevokk
    stevokk almost 7 years
    If XAML complains about not finding reference to your DateFormatter, make sure the xmls:local variable points to the right namespace. You can always make a new xmls reference called whatever you like to point to a specific file.
  • Nigel Ren
    Nigel Ren over 6 years
    Whilst code only answers may solve the original problem, some explanation would help a lot in understanding the method you've used and how it works.
  • Shahriar
    Shahriar over 5 years
    this is not a UWP solution
  • The Pademelon
    The Pademelon about 5 years
    StringFormat does not exist in UWP's Binding class. Furthermore, XML is not the same as XAML. XAML is an XML-based technology, but XAML and XML are not interchangeable terms.
  • BurnsBA
    BurnsBA almost 3 years
    This is for the Windows.UI.Xaml.Data namespace. For the IValueConverter in System.Windows.Data the method signature on Convert and ConvertBack changes the string language parameter to CultureInfo culture.