如何在 Xamarin 中使用 XAML 显示当前时间?

huangapple go评论113阅读模式
英文:

How do i display the current Time in Xamarin using xaml

问题

当我在DatePicker元素中使用DateTime.Today时,它正在运行并给我正确的输出,但当我在TimePicker元素中使用DateTime.Now时,它会返回错误。

  1. 错误
    位置 17:21。无法分配属性“Time”: 属性不存在,或无法分配,或值与属性之间的类型不匹配。

MainPage.xaml

<DatePicker Date="{x:Static sys:DateTime.Today}" />
<TimePicker Time="{x:Static sys:DateTime.Now}" />
英文:

When i use DateTime.Today in DatePicker element it's running and gives me proper output but when i use DateTime.Now in TimePicker element it returns me error

  1. Error
    Position 17:21. Cannot assign property "Time": Property does not exist, or is not assignable, or mismatching type between value and property

MainPage.xaml

&lt;DatePicker Date=&quot;{x:Static sys:DateTime.Today}&quot; /&gt;
&lt;TimePicker Time=&quot;{x:Static sys:DateTime.Now}&quot; /&gt;

答案1

得分: 5

这是因为TimePicker上的Time属性是TimeSpan类型,而DateTime.NowDateTime类型。您需要使用DateTime对象上的TimeOfDay属性。

编辑: 原来,您不能直接绑定到DateTime.Now.TimeOfDay,所以您需要以以下两种方式之一来做:

1)在页面的BindingContext目标上定义一个属性,使用此教程

或者2)给TimePicker起一个名字,在代码中设置其Time属性。

英文:

This is because the Time Property on the TimePicker is of type TimeSpan, while DateTime.Now is of type DateTime. You'll need to use the TimeOfDay property on a DateTime object.

Edit: Turns out, you can't bind to DateTime.Now.TimeOfDay directly, so you'll need to do it one of two other ways:

  1. Either define a Property on the target of the BindingContext of the page using this tutorial

or 2) Give the TimePicker a name and set the Time property on it in the code behind

huangapple
  • 本文由 发表于 2020年1月6日 19:38:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定