英文:
How do i display the current Time in Xamarin using xaml
问题
当我在DatePicker元素中使用DateTime.Today时,它正在运行并给我正确的输出,但当我在TimePicker元素中使用DateTime.Now时,它会返回错误。
- 错误
位置 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
- 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
<DatePicker Date="{x:Static sys:DateTime.Today}" />
<TimePicker Time="{x:Static sys:DateTime.Now}" />
答案1
得分: 5
这是因为TimePicker上的Time属性是TimeSpan类型,而DateTime.Now是DateTime类型。您需要使用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:
- Either define a Property on the target of the
BindingContextof the page using this tutorial
or 2) Give the TimePicker a name and set the Time property on it in the code behind
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论