Monday 10 July 2017

Roaming/Local Settings

Roaming Settings are exactly what they sound like, they're settings that roam with the user; meaning that if you use your app on your pc, and make some changes, than those changes will be reflected the next time you run the same app on your phone or tablet.

<Page
    x:Class="pc.NavigateExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBox x:Name="Input_TextBox" />
            <Button x:Name="Save_Button" Click="Save_Button_Click" Content="Save"/>
        </StackPanel>
    </Grid>
</Page>


above we created a very simple xaml page with a text box and a button, below is the implemented codebehind to save a roaming setting.

using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace pc.NavigateExample
{
    public sealed partial class MainPage : Page
    {
        public MainPage() {
            InitializeComponent();
            var RoamingSettings = ApplicationData.Current.RoamingSettings;

            if(RoamingSettings.Values.ContainsKey("paramter"))
            Input_TextBox.Text = RoamingSettings.Values["paramter"].ToString();
        }

        private void Save_Button_Click(object sender, RoutedEventArgs e)
        {
            var RoamingSettings = ApplicationData.Current.RoamingSettings;
            RoamingSettings.Values.Add("paramter", Input_TextBox.Text);
        }
    }
}


rather straight forward we use our roamingsettings which is just a key value dictionary. The roaming settings has a special key for desktop "HighPriority" which will let you sync that entry almost immediately however it only works for desktop app and really isn't all that useful. Now there is a limit to how much data you can roam and it's about 100k once your app passes this threshold it will simply stop syncing your data without warning.

If you want to instead store your settings locally than it's pretty much the same paradigm just use the LocalSetting dictionary instead.

using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace pc.NavigateExample
{
    public sealed partial class MainPage : Page
    {
        public MainPage() {
            InitializeComponent();
            var LocalSettings = ApplicationData.Current.LocalSettings;

            if(LocalSettings.Values.ContainsKey("paramter"))
            Input_TextBox.Text = LocalSettings.Values["paramter"].ToString();
        }

        private void Save_Button_Click(object sender, RoutedEventArgs e)
        {
            var LocalSettings = ApplicationData.Current.LocalSettings;
            LocalSettings.Values.Add("paramter", Input_TextBox.Text);
        }
    }
}


And that's all there is to that.