But first, don’t forget to set the SimpleStorage context within Android’s MainActivity:
SimpleStorage.SetContext(ApplicationContext);
The extension method Persist will have two arguments only (besides the bindable object obj itself): The property specifies which property to persist. And key defines the SimpleStorage edit group. The method will use the property name as storage key. The remainder is similar to the PersistentBindableObjectimplementation: The respective property is initialized with a value read from storage. And as soon as the property changes, it is written back to persistent storage. Since Persist returns the object itself, we can tightly attach the extension method to an object creation and even chain multiple calls.
public static class BindableObjectExtension
{
public static T Persist<T>(this T obj, BindableProperty property, string key) where T: BindableObject
{
var storage = SimpleStorage.EditGroup(key);
var propertyInfo = typeof(T).GetProperty(property.PropertyName);
propertyInfo.SetValue(obj, storage.Get<object>(property.PropertyName));
obj.PropertyChanged += (sender, e) => {
if (property.PropertyName == e.PropertyName)
storage.Put<object>(e.PropertyName, (object)propertyInfo.GetValue(obj));
};
return obj;
}
}Our MainPage contains three visual elements, each with one persistent property. For both, creating the object and persisting one of its properties, we need one line of code only!
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
new Entry().Persist(Entry.TextProperty, "entry"),
new Slider().Persist(Slider.ValueProperty, "slider"),
new Switch().Persist(Switch.IsToggledProperty, "switch"),
},
},
};