我在下面设置了 XAML 代码。
<Label Text="{Binding Date}"></Label>
<Label Text="{Binding Time}'}"></Label>
我想要2014年9月12日下午2:30这样的结果。
将代码更改为:
<Label Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}'}"></Label>
<Label Text="{Binding Time, StringFormat='{}{0:hh\\:mm}'}"></Label>
制作自定义 IValueConverter 实现:
public class DatetimeToStringConverter : IValueConverter
{
#region IValueConverter implementation
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return string.Empty;
var datetime = (DateTime)value;
//put your custom formatting here
return datetime.ToLocalTime().ToString("g");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
然后像这样使用它:
<ResourceDictionary>
<local:DatetimeToStringConverter x:Key="cnvDateTimeConverter"></local:DatetimeToStringConverter>
</ResourceDictionary>
...
<Label Text="{Binding Date, Converter={StaticResource cnvDateTimeConverter}}"></Label>
<Label Text="{Binding Time, Converter={StaticResource cnvDateTimeConverter}}"></Label>
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}'}" />
<Span Text=" " />
<Span Text="{Binding Time, StringFormat='{0:h:mm tt}'}" />
</FormattedString>
</Label.FormattedText>
</Label>