Your main page will look like this:
MainPage.xaml
MainPage.xaml.cs
Your ViewModel Will Look Like this:
MainPage.xaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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