Remark: Generally, it's recommended to store dates as 100 objects and not as other data types. You should use what's already there.
如果您不能或不想更改变量类型,则至少需要将其转换为属性.如果该值可能发生变化,则需要通过手动实现INotifyPropertyChanged接口或使用MVVM Community Toolkit‘S源生成器来使其可观察:
[ObservableProperty]
private long dateModified;
这将自动为您生成一个名为DateModified
的public
属性(请注意符号名称的小写和大写字母的差异),在引擎盖下看起来如下所示:
private long dateModified;
public long DateModified
{
get => dateModified;
set
{
if(dateModified.Equals(value) return;
dateModified = value;
OnPropertyChanged();
}
}
You can find more information about Source Generators on my 100.
然后,您可以实现将long
转换为DateTime
的value converter,例如:
public class LongToDateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value is long ticks)
{
return DateTime.FromTicks(ticks);
}
// Fallback value, could also be something else
return DateTime.MinValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
一百零二
然后,可以在XAML中使用此转换器将DateModified
属性转换为DateTime
对象,然后在绑定表达式中指定字符串格式:
<ContentPage.Resources>
<ResourceDictionary>
<converters:LongToDateTimeConverter x:Key="LongToDateConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<VerticalStackLayout>
<Label
Text="{Binding DateModified, Converter={StaticResource LongToDateConverter}, StringFormat='{0:M}, {0:yyyy}'}"/>
</VerticalStackLayout>
你可能需要try string format,直到你得到你需要的东西.有一份standard date and time formats人的大名单.如果我没记错的话,StringFormat='{0:M}, {0:yyyy}'}
应该产生类似May 28, 2023
的结果.
有几种其他方法可以做到这一点,例如,您也可以将属性转换为string
属性并绑定到该属性,或者更改转换器以生成已格式化的string
.但是,我建议使用上面的解决方案,因为它在字符串格式方面提供了更多的灵活性.在XAML中更改更容易,您甚至可以 for each 地区提供不同的格式,并且可以在绑定到相同属性的同时对不同的标签使用不同的格式.