PROWAREtech

articles » archived » xamarin » tutorial » page-10

Xamarin: Tutorial - Page 10

A guide for new Xamarin developers.

Saving Application State

Application.Properties is a dictionary of string keys and object values used for storing application data. This example uses MVVM.

<?xml version="1.0" encoding="utf-8"?>
<!--MainPageXaml.xaml-->
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml">

	<ContentPage.Padding>
		<OnPlatform x:TypeArguments="Thickness" iOS="20" Android="20, 0, 20, 20" />
	</ContentPage.Padding>

	<StackLayout>
		<Entry x:Name="entry"
					Text="{Binding EntryText}"
					Keyboard="Text"
					Placeholder="text that persists" />
		<Slider x:Name="slider"
					 Value="{Binding SliderValue}" />
	</StackLayout>
	
</ContentPage>
// MainPageXaml.xaml.cs
using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class MainPageXaml : ContentPage
	{
		public MainPageXaml()
		{
			InitializeComponent();
		}
	}
}
// ViewModel.cs
using System.ComponentModel;

namespace HelloXamarinForms
{
	class ViewModel : INotifyPropertyChanged
	{
		private string entryText;
		public string EntryText
		{
			get
			{
				return entryText;
			}
			set
			{
				if (value == entryText)
					return;
				entryText = value;
				OnPropertyChanged(nameof(EntryText));
			}
		}

		private double sliderValue;
		public double SliderValue
		{
			get
			{
				return sliderValue;
			}
			set
			{
				if (value == sliderValue)
					return;
				sliderValue = value;
				OnPropertyChanged(nameof(SliderValue));
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;
		void OnPropertyChanged(string propName)
		{
			PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
		}
	}
}
// App.xaml.cs
using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class App : Application
	{
		public App()
		{
			InitializeComponent();

			ViewModel viewModel = new ViewModel();

			if(Properties.ContainsKey("EntryText"))
			{
				viewModel.EntryText = (string)Properties["EntryText"];
			}
			if (Properties.ContainsKey("SliderValue"))
			{
				viewModel.SliderValue = (double)Properties["SliderValue"];
			}
			MainPage = new MainPageXaml()
			{
				BindingContext = viewModel
			};
		}

		protected override void OnStart()
		{
			// Handle when your app starts
		}

		protected override void OnSleep()
		{
			// Handle when your app sleeps
			ViewModel viewModel = (ViewModel)((MainPageXaml)MainPage).BindingContext;
			Properties["EntryText"] = viewModel.EntryText;
			Properties["SliderValue"] = viewModel.SliderValue;
		}

		protected override void OnResume()
		{
			// Handle when your app resumes
		}
	}
}

A Better Way: Serialization

Only two code files need to be modified to use XML serialization.

// ViewModel.cs
using System.Xml.Serialization;
using System.ComponentModel;
using System.IO;

namespace HelloXamarinForms
{
	public class ViewModel : INotifyPropertyChanged
	{
		private string entryText;
		public string EntryText
		{
			get
			{
				return entryText;
			}
			set
			{
				if (value == entryText)
					return;
				entryText = value;
				OnPropertyChanged(nameof(EntryText));
			}
		}

		private double sliderValue;
		public double SliderValue
		{
			get
			{
				return sliderValue;
			}
			set
			{
				if (value == sliderValue)
					return;
				sliderValue = value;
				OnPropertyChanged(nameof(SliderValue));
			}
		}

		public string Serialize()
		{
			XmlSerializer xmlSerial = new XmlSerializer(typeof(ViewModel));
			using (StringWriter strWriter = new StringWriter())
			{
				xmlSerial.Serialize(strWriter, this);
				return strWriter.GetStringBuilder().ToString();
			}
		}

		public static ViewModel Deserialize(string xmlString)
		{
			XmlSerializer xmlSerial = new XmlSerializer(typeof(ViewModel));
			using (StringReader strReader = new StringReader(xmlString))
			{
				return (ViewModel)xmlSerial.Deserialize(strReader);
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;
		void OnPropertyChanged(string propName)
		{
			PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
		}
	}
}
// App.xaml.cs
using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class App : Application
	{
		public App()
		{
			InitializeComponent();

			ViewModel viewModel;

			if (Properties.ContainsKey(nameof(ViewModel)))
			{
				viewModel = ViewModel.Deserialize((string)Properties[nameof(ViewModel)]);
			}
			else
			{
				viewModel = new ViewModel();
			}
			MainPage = new MainPageXaml()
			{
				BindingContext = viewModel
			};
		}

		protected override void OnStart()
		{
			// Handle when your app starts
		}

		protected override void OnSleep()
		{
			// Handle when your app sleeps
			ViewModel viewModel = (ViewModel)((MainPageXaml)MainPage).BindingContext;
			Properties[nameof(ViewModel)] = viewModel.Serialize();
		}

		protected override void OnResume()
		{
			// Handle when your app resumes
		}
	}
}
<<<[Page 10 of 11]>>>

PROWAREtech

Hello there! How can I help you today?
Ask any question
This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE