Thursday, 12 July 2018

MVVM Example 3 A new Approach to property Changed

MainPage.Xaml will look Like this:

<?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:MvvmExample3"
x:Class="MvvmExample3.MainPage">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness"
iOS="20, 40, 20, 20"
Android="20, 20, 20, 20"
WinPhone="20, 20, 20, 20" />
</ContentPage.Padding>
<ContentPage.Content>
<StackLayout VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
Orientation="Vertical"
Spacing="15">
<Label Text="PersonName"/>
<Entry Text="{Binding PersonName}" Placeholder="Full Name"/>
<Label Text="WorksIn"/>
<Entry Text="{Binding WorksIn}" Placeholder="Your Website"/>
<StackLayout Orientation="Horizontal" Spacing="10">
<Label Text="Save Data?"/>
<Switch IsToggled="{Binding MySwitch}"/>
</StackLayout>
<Label Text="{Binding DisplayMessage}"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub
MainPage.Xaml.cs will look Like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace MvvmExample3
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new ViewModel.MyNewViewModel();
}
}
}
MyNewViewModel.cs will look Like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
namespace MvvmExample3.ViewModel
{
public class MyNewViewModel : INotifyPropertyChanged
{
string firstname = "Samir";
string lastname = "Xamarin University";
bool myswitch;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public bool MySwitch
{
get { return myswitch; }
set
{
myswitch = value;
OnPropertyChanged();
OnPropertyChanged(nameof(DisplayMessage));
}
}
public string PersonName
{
get { return firstname; }
set
{
firstname = value;
OnPropertyChanged();
OnPropertyChanged(nameof(DisplayMessage));
}
}
public string WorksIn
{
get { return lastname; }
set
{
lastname = value;
OnPropertyChanged();
OnPropertyChanged(nameof(DisplayMessage));
}
}
public string DisplayMessage
{
get
{
return $"Mr {PersonName}" + $"Worksin"
+ $"{WorksIn}"
+ $"{(myswitch ? "saved to database" : " is not saved to database")}";
}
}
}
}

No comments:

Post a Comment