绑定上的 StringFormat [英] StringFormat on Binding
问题描述
查看:
<TextBlock Text="{Binding Date}"/>
我想将日期格式化为dd/MM/yyyy",换句话说,没有时间.
I want to format the Date to "dd/MM/yyyy", in other words, without the time.
我试过了:<TextBlock Text="{Binding Date, StringFormat={}{0:dd/MM/yyyy}}"/>
,但它不起作用.
I tried it: <TextBlock Text="{Binding Date, StringFormat={}{0:dd/MM/yyyy}}"/>
, but it doesn't work.
给我一个错误:在绑定"类型中找不到属性StringFormat".
Gives me an error: The property 'StringFormat' was not found in type 'Binding'.
推荐答案
最好和最简单的方法是使用转换器,您可以将日期传递给该转换器并返回格式化的字符串.在例如MyNamespace.Converters
命名空间:
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();
}
}
并在您的 xaml 中引用转换器并添加以下转换器:
And in your xaml just reference the converter and add the following converter:
xmlns:conv="using:MyNamespace.Converters"
在你的 xaml 页面和 page.resources 中添加这个
in your xaml page and in page.resources add this
<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/>
<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/>
这篇关于绑定上的 StringFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!