dev*_*033 19 c# xaml string-formatting date-formatting uwp
视图:
<TextBlock Text="{Binding Date}"/>
Run Code Online (Sandbox Code Playgroud)
我希望将日期格式化为"dd/MM/yyyy",换句话说,没有时间.
我试过了:<TextBlock Text="{Binding Date, StringFormat={}{0:dd/MM/yyyy}}"/>
但它不起作用.
给我一个错误:在'Binding'类型中找不到属性'StringFormat'.
小智 20
最好和最简单的方法是使用转换器传递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();
}
}
Run Code Online (Sandbox Code Playgroud)
在您的xaml中只需引用转换器并添加以下转换器:
xmlns:conv="using:MyNamespace.Converters"
Run Code Online (Sandbox Code Playgroud)
在你的xaml页面和page.resources中添加这个
<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/>
<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/>
Run Code Online (Sandbox Code Playgroud)
小智 8
我知道这已经晚了,但我有同样的问题并提出了这个解决方案。也许不是最短但纯粹的 XAML。
<TextBlock>
<Run Text="{x:Bind Foo.StartDate.Day}"/>.<Run Text="{x:Bind Foo.StartDate.Month}"/>.<Run Text="{x:Bind Foo.StartDate.Year}"/>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
从 14393 开始,您可以使用x:Bind 中的函数。
这意味着您可以将日期格式化为:
Text="{x:Bind sys:String.Format('{0:dd/MM/yyyy}', ViewModel.Date)}"
Run Code Online (Sandbox Code Playgroud)
只需确保您已包含对系统命名空间的引用:
<Page
xmlns:sys="using:System"
...
Run Code Online (Sandbox Code Playgroud)
没有命名属性StringFormat
的绑定类.您可以使用Converter和ConverterParameter执行此操作.您可以参考格式化或转换数据值进行显示.
例如,在这里,我将a的日期绑定到a 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>
Run Code Online (Sandbox Code Playgroud)
代码隐藏,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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17113 次 |
最近记录: |