绑定时的StringFormat

本文关键字:StringFormat 定时 绑定 | 更新日期: 2023-09-27 18:29:41

视图:

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

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

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

出现错误:在类型"Binding"中找不到属性"StringFormat"。

绑定时的StringFormat

最好也是最简单的方法是使用一个转换器,将Date传递到该转换器,然后返回格式化的字符串。例如,在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页面和页面中。资源添加此

<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/>
<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/>

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

    <TextBlock>
        <Run Text="{x:Bind Foo.StartDate.Day}"/>.<Run Text="{x:Bind Foo.StartDate.Month}"/>.<Run Text="{x:Bind Foo.StartDate.Year}"/>
    </TextBlock>
Binding类中没有名为StringFormat的属性。您可以使用Converter和ConverterParameter来执行此操作。您可以参考格式化或转换要显示的数据值。

例如,在这里,我将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类:

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

自14393年以来,您可以使用x:Bind中的函数。

这意味着您可以将日期格式设置为:

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

只需确保您已包含对System命名空间的引用:

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

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

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

这里有一个很好的例子:

MSDN 中的示例

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

xmlns:conv="using:MyNamespace.Converters"

并像这样使用:

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

其余部分应与链接中的示例保持相同。

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