Xamarin数据绑定DateTime.Now不起作用

时间:2019-04-12 15:38:28

标签: xamarin

我正在学习Xamarin数据绑定并面对以下代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             xmlns:local="clr-namespace:ViewModel_ex"
             x:Class="ViewModel_ex.MainPage">
    <StackLayout BindingContext="{x:Static sys:DateTime.Now}" 
                 HorizontalOptions="Center"
                 VerticalOptions="Center">
        <Label Text="{Binding Year, StringFormat='The year is {0}'}"/>
        <Label Text="{Binding Month, StringFormat='The month is {0}'}"/>
        <Label Text="{Binding Day, StringFormat='The day is {0}'}"/>
        <Label Text="{Binding Time, StringFormat='The time is {0}'}"/>
    </StackLayout>
</ContentPage>

我所得到的显示如下:

result1

我想知道为什么时间在浪费?

1 个答案:

答案 0 :(得分:2)

Time下没有属性Datetime.Now。您必须使用

 <StackLayout BindingContext="{x:Static sys:DateTime.Now}" 
                 HorizontalOptions="Center"
                 VerticalOptions="Center">
        <Label Text="{Binding Year, StringFormat='The year is {0}'}"/>
        <Label Text="{Binding Month, StringFormat='The month is {0}'}"/>
        <Label Text="{Binding Day, StringFormat='The day is {0}'}"/>
        <Label Text="{Binding TimeOfDay, StringFormat='The time is {0}'}"/>
    </StackLayout>

enter image description here