Jeremy Parker
Jeremy Parker

Reputation: 418

Xamarin data binding DateTime.Now not working

I'm learning Xamarin data binding and facing the below code:

<?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>

What I got is shown the below:

result1

I'm wondering why time is losing?

Upvotes: 0

Views: 398

Answers (1)

GeralexGR
GeralexGR

Reputation: 3582

There is not a property Time under Datetime.Now. You must use

 <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

Upvotes: 2

Related Questions