绑定上的 StringFormat

StringFormat on Binding

查看:

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

我想将日期格式化为 "dd/MM/yyyy",换句话说,没有时间。

我试过了:<TextBlock Text="{Binding Date, StringFormat={}{0:dd/MM/yyyy}}"/>,但是不行。

给我一个错误: 属性 'StringFormat' 未在类型 'Binding' 中找到。

最好和最简单的方法是使用一个转换器,您将日期传递给该转换器并取回格式化的字符串。例如MyNamespace.Converters 命名空间:

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

并且在您的 xaml 中仅引用转换器并添加以下转换器:

xmlns:conv="using:MyNamespace.Converters" 

在您的 xaml 页面和 page.resources 中添加这个

<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/>

<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/>

Binding class. You can use Converter and ConverterParameter to do this. You can refer to Formatting or converting data values for display 中没有名为 StringFormat 的 属性。

例如这里,我将 DatePicker 的日期绑定到 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>

后面的代码,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;
    }
}

这里有一个很好的例子:

Example from MSDN

如果您的转换器 class 在不同的命名空间中(建议在单独的文件夹中),您可以添加

xmlns:conv="using:MyNamespace.Converters"

并像这样使用它:

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

其余部分应与 link 中的示例保持一致。

为什么要复杂化?您可以使用已编译的数据绑定

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

我知道这已经晚了,但我有同样的问题并提出了这个解决方案。也许不是最短但纯粹的 XAML.

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

StringFormat 的好处在于它允许您指定输出格式。这是我使用的转换器,可让您指定格式。

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

如何使用(多种格式的示例):

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

试试这个,

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

您可以在 xml 中完成此操作。这里...

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

从14393开始,可以使用functions in x:Bind.

这意味着您可以像这样格式化日期:

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

只需确保包含对系统命名空间的引用:

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