How to bind in XAML a property of a page?

nicktheonenicktheone Member ✭✭

I want to bind the text property of my Label eorzeaTimeNowLabel to the property DateTime EorzeaTimeNow of my main class; in particular I'm unable to understand to what and how I should set my binding context. I'm sure it's a simple solution but it makes me scratch me head hard.

XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Eorzea_Gatherer.Pages.HomePage"
         BackgroundColor="#F4F4F4">
<ContentPage.Content>
    <Grid Padding="30">
        <StackLayout x:Name="SL"
                     HorizontalOptions="Center"
                     VerticalOptions="Center">
            <Label Text="Eorzea Time" 
                   TextColor="#8E8E93"
                   FontFamily="SegoeUI"
                   HorizontalOptions="Center">
                <Label.FontSize>
                    <OnIdiom x:TypeArguments="x:Double" Phone="13" Tablet="25"/>
                </Label.FontSize>
            </Label>
            <Label x:Name="eorzeaTimeNowLabel" 
           Text="Eorzea Time"
                   TextColor="#171717"
                   FontFamily="Gilroy-Light"
                   HorizontalOptions="Center">
                <Label.FontSize>
                    <OnIdiom x:TypeArguments="x:Double" Phone="37" Tablet="71"/>
                </Label.FontSize>
            </Label>
        </StackLayout>
    </Grid>
</ContentPage.Content>

Code behind:

namespace Eorzea_Gatherer.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        public DateTime EorzeaTimeNow { get; set; }

        public HomePage()
        {
            InitializeComponent ();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            //Start the timer that calculates Eorzea Time
            Device.StartTimer(TimeSpan.FromMilliseconds(1000), () =>
            {
                EorzeaTimeNow = DateTime.Now.ToEorzeaTime();
                eorzeaTimeNowLabel.Text = EorzeaTimeNow.ToString("hh:mm tt");

                return true;
            });
        }
    }
}

Best Answer

Answers

  • nicktheonenicktheone Member ✭✭

    Perfect response, thanks a lot! It was definitely harder than I thought.

Sign In or Register to comment.