【问题标题】:Xamarin.Forms - Changing values from SQLite before displaying (DateTime)Xamarin.Forms - 在显示之前从 SQLite 更改值(日期时间)
【发布时间】:2019-11-20 02:19:45
【问题描述】:

我有一个问题,希望你能帮助我。

我在 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 对象,并计算从今天到给定日期还剩下多少天。

【问题讨论】:

    标签: c# sqlite xaml xamarin.forms


    【解决方案1】:

    首先,在数据库中将日期存储为 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;
          }
        }
    }
    

    【讨论】:

    • 非常感谢。当然,这解决了我的问题。我使用了您的代码并使用了“Binding DaysLeft”而不是“Binding Date”。
    • 日期添加和显示工作正常。不幸的是,当我想添加一个新项目,但我没有选择日期(我没有单击 DatePicker)并单击保存 -> 我有一个异常:未处理的异常:System.Reflection.TargetInvocationException:异常已被抛出调用的目标。
    • 这是一个完全不同的问题——你应该问一个新问题
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多