c# - Xamarin.Forms - 在显示之前从 SQLite 更改值(日期时间)
问题描述
我有一个问题,希望你能帮助我。
我在 Xamarin.Forms 中的应用程序可以添加到 sqlite:
public class Product
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Text { get; set; }
public string Details { get; set; }
public string Date { get; set; }
}
使用以下方法添加此数据:
<Editor Placeholder="Enter text" Text="{Binding Text}" />
<Editor Placeholder="Enter details" Text="{Binding Details}" />
<DatePicker Date="{Binding Date, Mode=TwoWay}" Format="dd/MM/yyyy" />
在另一个页面上,我使用 ListView 显示它们:
<Label Text="{Binding Text}" />
<Label Text="{Binding Details}" />
<Label Text="{Binding Date}" />
日期显示格式为:01/01/2017 00:00:00
我希望能够在此日期文本出现之前对其进行更改。例如,我想将此字符串日期转换为 DateTime 对象并计算从今天到给定日期还剩下多少天。
解决方案
首先,将日期存储为数据库中的 DateTime 类型而不是字符串通常是最佳实践。
也就是说,有很多方法可以解决这个问题。一种是将只读属性添加到您的模型或 ViewModel
public class Product
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Text { get; set; }
public string Details { get; set; }
public string Date { get; set; }
// tell sqlite to ignore this column
[Ignore]
public int DaysLeft {
get {
// should add error handling here in case
// date format is bad
var date = DateTime.Parse(Date);
// diff will be a TimeSpan
var diff = DateTime.Now - date;
// might want to add logic to handle negative values
return diff.Days;
}
}
}
推荐阅读
- python - Python Selenium 使用 Try-Loop 具有不同 xpath 的一个元素
- javascript - 构造函数的原型方法中保存的 this 的值在哪里?
- r - 如何更改 ComplexHeatmap 中的边框大小?
- python-3.x - Ortools CVRP 重用旧车
- css - CSS属性值中的“--”破折号是什么意思
- python - 如何在python中动态生成键并将值分配给嵌套字典
- javascript - 如何查看在浏览器中出现错误的 js 行?
- javascript - 如何重构“if x return x”语句
- xamarin.android - Xamarin 中的 Android .aar 绑定库
- javascript - 导入静态函数/类时尝试导入错误