StringFormat on Binding

只谈情不闲聊 提交于 2019-11-29 16:39:55

问题


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'.


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



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



回答3:


why to complicate? You can use compiled data binding

{x:Bind ViewModel.PropertyWithDateTime.ToString("....")}



回答4:


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>



回答5:


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"
     ...



回答6:


There is an excellent example here:

Example from MSDN

if your converter class is in a different namespace (as suggested to be in a separate folder) you can add

xmlns:conv="using:MyNamespace.Converters"

and use it like this:

<UserControl.Resources>
  <conv:DateToStringConverter x:Key="Converter1"/>
</UserControl.Resources>

the rest should stay the same as in the example from the link.




回答7:


You can do this in xml itself. Here...

<DatePicker 
SelectedDate="{Binding Date, Mode=TwoWay}" 
Text="{Binding ., StringFormat='dd/MM/yyyy'}"/>



回答8:


Try this,

<Label x:Name="LblEstEndTime" Text="{Binding EndTime, StringFormat='Est. End Time: {0:MM/dd/yy h:mm tt}'}" Style="{StaticResource ListCellSubTitleStyle}" VerticalOptions="EndAndExpand" />




回答9:


The nice thing about StringFormat is that it allows you to specify the format of the output. Here is a converter I use that allows you to specify the format.

public sealed class DateTimeToStringConverter : IValueConverter
{
    public static readonly DependencyProperty FormatProperty =
        DependencyProperty.Register(nameof(Format), typeof(bool), typeof(DateTimeToStringConverter), new PropertyMetadata("G"));

    public string Format { get; set; }

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value is DateTime dateTime && value != null)
        {
            return dateTime.ToString(Format);
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return DateTime.ParseExact(value.ToString(), Format, CultureInfo.CurrentCulture);
    }
}

How to use (example with multiple formats):

<Page.Resources>
    <ResourceDictionary>
        <converters:DateTimeToStringConverter 
            x:Name="dateStringConverter" 
            Format="dd-MM-yyyy" />
        <converters:DateTimeToStringConverter
            x:Name="timeStringConverter"
            Format="HH:mm" />
    </ResourceDictionary>
</Page.Resources>

<!-- Display the date -->
<TextBlock Text="{Binding Path=Date, Converter={StaticResource dateStringConverter}}" />    

<!-- Display the time -->
<TextBlock Text="{Binding Path=Date, Converter={StaticResource timeStringConverter}}" />


来源:https://stackoverflow.com/questions/34713126/stringformat-on-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!