As suggested in the comments you could do this with a ValueConverter.
Write a converter similar to this, in your shared code.
public class TicksToDateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!Int64.TryParse(value, out long ticks))
return DatTime.Now;
// TODO you can do a ToString and format it you want here but also in XAML
return new DateTime(ticks);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Not needed
throw new NotImplementedException();
}
}
Now in your XAML, declare te value convter like this under the root of your page, I'm assuming it's a ContentPage
.
<ContentPage.Resources>
<ResourceDictionary>
<local:TicksToDateTimeConverter x:Key="TicksConverter" />
</ResourceDictionary>
</ContentPage.Resources>
And don't forget to declare the local
namespace in your page root like: xmlns:local="clr-namespace:YourApp.Namespace"
, which should be the full namespace, without the class name to your converter class.
To finally use the converter in your layout, do this:
<StackLayout>
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding createdTime, Converter={StaticResource TicksConverter}}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Depending on whether or not you return a string from the converter or a DateTime
, in the latter case you can also format it here in XAML, like so:
<Label Text="{Binding createdTime, Converter={StaticResource TicksConverter}, StringFormat='{0:dd-MM-yyyy}'}"/>
Or you could choose to do it differently altogether and convert the value inside the model that you bind to the ViewCell
.