Thursday, 12 July 2018

MVVM Example 2 Connecting With View Model

Your main page will look like this:
MainPage.xaml
<?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:local="clr-namespace:MvvmExample2"
x:Class="MvvmExample2.MainPage">
<StackLayout>
<!-- Place new controls here -->
<Label Text="{Binding DateTime, StringFormat='{0:T}'}"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center"/>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace MvvmExample2
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MyNewMvvmViewModel();
}
}
}
Your ViewModel Will Look Like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Xamarin.Forms;
namespace MvvmExample2
{
public class MyNewMvvmViewModel : INotifyPropertyChanged
{
//ViewModel generally implement the INotifyPropertyChanged interface,
//which means that the class fires a PropertyChanged event whenever one of its properties changes.
public MyNewMvvmViewModel()
{
this.DateTime = DateTime.Now;
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
this.DateTime = DateTime.Now;
return true;
});
}
DateTime dateTime;
public event PropertyChangedEventHandler PropertyChanged;
public DateTime DateTime
{
set
{
if (dateTime != value)
{
dateTime = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("DateTime"));
}
}
}
get
{
return dateTime;
}
}
}
}


No comments:

Post a Comment