Pliki i foldery w Windows Phone 8 - Zapis i odczyt ustawień  Udostępnij na: Facebook

Pobierz i uruchom

Tłumaczenie na podstawie How to create a settings page for Windows Phone: Aurelia Tokarek

Opublikowano: 2013-01-29

W tym odcinku nauczysz się odczytywać i zapisywać ustawienia w aplikacji.

Tworzenie klasy Settings

Pierwszym krokiem w tworzeniu ustawień strony dla Twojej aplikacji Windows Phone jest utworzenie klasy przechowującej ustawienia oraz zapisującej i ładującej ustawienia z lokalnego folderu. Więcej informacji o przechowywaniu ustawień w kluczowych wartościach w  folderze lokalnym znajdziesz w IsolatedStorageSettings. Aby wzbogacić swoje wiadomości na temat przechowywania danych zapoznaj się z Data for Windows Phone.

Klasa będzie zawierać metodę do dodawania i aktualizowania wartości w folderze lokalnym. W poniższym kodzie nazwana została AddOrUpdateValue. Jest także metoda do odczytywania wartości lub przypisania wartości domyślnej, jeśli wartość nie została wcześniej określona. W poniższym kodzie nazwana została GetValueOrDefault.

Dla każdego ustawienia lub właściwości istnieją funkcje dostępowe. Poniższy kod zawiera ich kilka. Nazwane zostały: CheckBoxSetting, ListBoxSetting oraz PasswordSetting. Możesz dołączyć własne właściwości poprzez dodanie własnej funkcji dostępu. Dla każdego ustawienia istnieje ciąg zawierający zdefiniowane nazwy kluczowe oraz stałe, definiujące wartość domyślną.

using System;
using System.IO.IsolatedStorage;
using System.Diagnostics;
using System.Collections.Generic;

namespace SettingsSample
{
        public class AppSettings
        {
            // Our settings
            IsolatedStorageSettings settings;

            // The key names of our settings
                const string CheckBoxSettingKeyName = "CheckBoxSetting";
                const string ListBoxSettingKeyName = "ListBoxSetting";
                const string RadioButton1SettingKeyName = "RadioButton1Setting";
                const string RadioButton2SettingKeyName = "RadioButton2Setting";
                const string RadioButton3SettingKeyName = "RadioButton3Setting";
                const string UsernameSettingKeyName = "UsernameSetting";
                const string PasswordSettingKeyName = "PasswordSetting";

                // The default value of our settings
                const bool CheckBoxSettingDefault = true;
                const int ListBoxSettingDefault = 0;
                const bool RadioButton1SettingDefault = true;
                const bool RadioButton2SettingDefault = false;
                const bool RadioButton3SettingDefault = false;
                const string UsernameSettingDefault = "";
                const string PasswordSettingDefault = "";

            /// <summary>
            /// Constructor that gets the application settings.
            /// </summary>
            public AppSettings()
            {
                // Get the settings for this application.
                settings = IsolatedStorageSettings.ApplicationSettings;
            }

            /// <summary>
            /// Update a setting value for our application. If the setting does not
            /// exist, then add the setting.
            /// </summary>
            /// <param name="Key"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            public bool AddOrUpdateValue(string Key, Object value)
            {
                bool valueChanged = false;

                // If the key exists
                if (settings.Contains(Key))
                {
                    // If the value has changed
                    if (settings[Key] != value)
                    {
                        // Store the new value
                        settings[Key] = value;
                        valueChanged = true;
                    }
                }
                // Otherwise create the key.
                else
                {
                    settings.Add(Key, value);
                    valueChanged = true;
                }
            return valueChanged;
            }

            /// <summary>
            /// Get the current value of the setting, or if it is not found, set the 
            /// setting to the default setting.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="Key"></param>
            /// <param name="defaultValue"></param>
            /// <returns></returns>
            public T GetValueOrDefault<T>(string Key, T defaultValue)
            {
                T value;

                // If the key exists, retrieve the value.
                if (settings.Contains(Key))
                {
                    value = (T)settings[Key];
                }
                // Otherwise, use the default value.
                else
                {
                    value = defaultValue;
                }
                return value;
            }

            /// <summary>
            /// Save the settings.
            /// </summary>
            public void Save()
            {
                settings.Save();
            }


            /// <summary>
            /// Property to get and set a CheckBox Setting Key.
            /// </summary>
            public bool CheckBoxSetting
            {
                get
                {
                    return GetValueOrDefault<bool>(CheckBoxSettingKeyName, CheckBoxSettingDefault);
                }
                set
                {
                if (AddOrUpdateValue(CheckBoxSettingKeyName, value))
                {
                    Save();
                }
                }
            }


            /// <summary>
            /// Property to get and set a ListBox Setting Key.
            /// </summary>
            public int ListBoxSetting
            {
                get
                {
                    return GetValueOrDefault<int>(ListBoxSettingKeyName, ListBoxSettingDefault);
                }
                set
                {
                    if (AddOrUpdateValue(ListBoxSettingKeyName, value))
                    {
                        Save();
                    }
                }
                }


            /// <summary>
            /// Property to get and set a RadioButton Setting Key.
            /// </summary>
            public bool RadioButton1Setting
            {
                get
                {
                    return GetValueOrDefault<bool>(RadioButton1SettingKeyName, RadioButton1SettingDefault);
                }
                set
                {
                    if (AddOrUpdateValue(RadioButton1SettingKeyName, value))
                    {    
                        Save();
                    }
                }
                }


            /// <summary>
            /// Property to get and set a RadioButton Setting Key.
            /// </summary>
            public bool RadioButton2Setting
            {
                get
                {
                    return GetValueOrDefault<bool>(RadioButton2SettingKeyName, RadioButton2SettingDefault);
                }
                set
                {
                    if (AddOrUpdateValue(RadioButton2SettingKeyName, value))
                    {
                        Save();
                    }
                }
            }

            /// <summary>
            /// Property to get and set a RadioButton Setting Key.
            /// </summary>
            public bool RadioButton3Setting
            {
                get
                {
                    return GetValueOrDefault<bool>(RadioButton3SettingKeyName, RadioButton3SettingDefault);
                }
                set
                {
                    if (AddOrUpdateValue(RadioButton3SettingKeyName, value))
                    {
                        Save();
                    }
                }
            }

            /// <summary>
            /// Property to get and set a Username Setting Key.
            /// </summary>
            public string UsernameSetting
            {
                get
                {
                    return GetValueOrDefault<string>(UsernameSettingKeyName, UsernameSettingDefault);
                }
                set
                {
                    if (AddOrUpdateValue(UsernameSettingKeyName, value))
                    {
                        Save();
                    }
                }
            }

            /// <summary>
            /// Property to get and set a Password Setting Key.
            /// </summary>
            public string PasswordSetting
            {
                get
                {
                    return GetValueOrDefault<string>(PasswordSettingKeyName, PasswordSettingDefault);
                }
                set
                {
                    if (AddOrUpdateValue(PasswordSettingKeyName, value))
                {
                    Save();
                }
                }
            }
        }
}

Tworzenie strony ustawień nie wymagającej przycisku potwierdzenia

Dla ustawień, które nie wymagają potwierdzenia przez użytkownika, możesz użyć powiązania danych (data binding) do natychmiastowej zmiany ustawień i zapisania wartości w folderze lokalnym. Wszystkie zmiany wykonywane są w języku XAML dla strony ustawień. Zauważ, że tryb powiązania danych TwoWay wprowadza zmiany ze skutkiem natychmiastowym.

Uwaga!

Wytyczne o projektowaniu UI ustawień strony znajdziesz w Design library for Windows Phone.

Rozpocznij pracę poprzez dodaniexmlns:local="clr-namespace:SettingsSample" deklaracji przestrzeni nazw elementu phone:PhoneApplicationPage Twojej strony. Poniższy kod pokazuje deklarację przestrzeni nazw ze strony SettingsWithoutConfirmation.xaml:

<phone:PhoneApplicationPage 
    x:Class="SettingsSample.SettingsWithoutConfirmation"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"

    xmlns:local="clr-namespace:SettingsSample"

    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

Następnie dodaj lokalny zasób <local:AppSettings x:Key="appSettings"></local:AppSettings>:

<phone:PhoneApplicationPage.Resources>
    <local:AppSettings x:Key="appSettings"></local:AppSettings>
</phone:PhoneApplicationPage.Resources>

Dla każdego ustawienia na stronie ustaw powiązanie danych z właściwościami kontrolek:

<Grid x:Name="ContentGrid" Grid.Row="1">
    <CheckBox Content="CheckBox Setting" Height="Auto" HorizontalAlignment="Left" Margin="60,20,0,0" Name="checkBoxSetting" VerticalAlignment="Top"
        IsChecked="{Binding Source={StaticResource appSettings}, Path=CheckBoxSetting, Mode=TwoWay}"  />

    <ListBox Height="140" HorizontalAlignment="Left" Margin="70,150,0,0" Name="listBoxSetting" 
        VerticalAlignment="Top" Width="360"  SelectedIndex="{Binding Source={StaticResource appSettings}, Path=ListBoxSetting, Mode=TwoWay}">

        <ListBoxItem Content="Times New Roman" FontSize="24" FontFamily="Times New Roman" />
        <ListBoxItem Content="Arial" FontSize="24" FontFamily="Arial" />
        <ListBoxItem Content="Comic Sans MS" FontSize="24" FontFamily="Comic Sans MS" />
    </ListBox>

    <RadioButton Content="Choice One" Height="Auto" HorizontalAlignment="Left" Margin="60,0,0,235" Name="radioButton1" VerticalAlignment="Bottom" GroupName="GroupOne" IsChecked="{Binding Source={StaticResource appSettings}, Path=RadioButton1Setting, Mode=TwoWay}" />
    <RadioButton Content="Choice Two" Height="Auto" HorizontalAlignment="Left" Margin="60,350,0,0" Name="radioButton2" VerticalAlignment="Top" GroupName="GroupOne" IsChecked="{Binding Source={StaticResource appSettings}, Path=RadioButton2Setting, Mode=TwoWay}"/>
    <RadioButton Content="Choice Three" Height="Auto" HorizontalAlignment="Left" Margin="60,400,0,0" Name="radioButton3" VerticalAlignment="Top" GroupName="GroupOne" IsChecked="{Binding Source={StaticResource appSettings}, Path=RadioButton3Setting, Mode=TwoWay}"/>
</Grid>

Żaden dodatkowy kod nie jest potrzebny. Strona ustawień jest kompletna.

Tworzenie strony ustawień wymagającej przycisku potwierdzenia

Ustawienia wymagające wprowadzenia tekstu, takie jak nazwa użytkownika lub hasło, mogą wymagać od użytkownika przyciśnięcia przycisku potwierdzającego wprowadzenie danych. Dla takich ustawień strony możesz dodać przyciski OK i Cancel w menu aplikacji.

Dla stron wymagających od użytkownika przyciśnięcia przycisku potwierdzającego, możesz użyć powiązania danych do ładowania aktualnej wartości, ale zmiany, których dokonuje użytkownik, nie mogą być wprowadzane natychmiast.

Zacznij od deklaracji przestrzeni nazw xmlns:local=”clr-namespace:SettingsSample” elementu phone:PhoneApplicationPage na stronie. Poniższy kod pokazuje deklarację przestrzeni nazw ze strony SettingsWithConfirmation.xaml:

<phone:PhoneApplicationPage 
    x:Class="SettingsSample.SettingsWithConfirmation"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"

    xmlns:local="clr-namespace:SettingsSample"

    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">
Następnie dodaj zasoby lokalne <local:AppSettings x:Key=”appSettings></local:AppSettings>

Następnie, dodaj lokalny zasób <local:AppSettings x:Key="appSettings"></local:AppSettings>:

<phone:PhoneApplicationPage.Resources>
    <local:AppSettings x:Key="appSettings"></local:AppSettings>
</phone:PhoneApplicationPage.Resources>

Dla każdego ustawienia na stronie ustaw powiązanie danych z właściwością kontrolki:

<Grid x:Name="ContentGrid" Grid.Row="1">
    <TextBlock Height="60" HorizontalAlignment="Left" Margin="65,12,0,0" Name="textBlock1" Text="Username" VerticalAlignment="Top" Width="169" />
    <TextBox Height="78" HorizontalAlignment="Left" Margin="60,60,0,0" Name="textBoxUsername" 
        Text="{Binding Path=UsernameSetting, Mode=OneWay, Source={StaticResource appSettings}}" VerticalAlignment="Top" Width="274"  />

    <TextBlock Height="60" HorizontalAlignment="Left" Margin="65,160,0,0" Name="textBlock2" Text="Password" VerticalAlignment="Top" Width="169" />
    <PasswordBox Height="78" HorizontalAlignment="Left" Margin="60,208,0,0" Name="passwordBoxPassword" 
        Password="{Binding Path=PasswordSetting, Mode=OneWay, Source={StaticResource appSettings}}" VerticalAlignment="Top" Width="274" />
</Grid>

W konstruktorze strony dodaj pasek aplikacji, posiadający przyciski OK i Cancel:

public SettingsWithConfirmation()
{

    InitializeComponent();

    // Add an Application Bar that has a 'done' confirmation button and 
    // a 'cancel' button
    ApplicationBar = new ApplicationBar();
    ApplicationBar.IsMenuEnabled = true;
    ApplicationBar.IsVisible = true;
    ApplicationBar.Opacity = 1.0;

    ApplicationBarIconButton doneButton = new ApplicationBarIconButton(new Uri("/Images/appbar.check.rest.png", UriKind.Relative));
    doneButton.Text = "done";
    doneButton.Click += new EventHandler(doneButton_Click);

    ApplicationBarIconButton cancelButton = new ApplicationBarIconButton(new Uri("/Images/appbar.cancel.rest.png", UriKind.Relative));
    cancelButton.Text = "cancel";
    cancelButton.Click += new EventHandler(cancelButton_Click);

    ApplicationBar.Buttons.Add(doneButton);
    ApplicationBar.Buttons.Add(cancelButton);
}

Jeśli użytkownik potwierdzi zmiany, wartości zostaną zapisane:

void doneButton_Click(object sender, EventArgs e)
{
    settings.UsernameSetting = textBoxUsername.Text;
    settings.PasswordSetting = passwordBoxPassword.Password;
    NavigationService.GoBack();
}
Jednakże jeśli użytkownik anuluje zmiany, zostanie przeniesiony poza stronę.
C#
void cancelButton_Click(object sender, EventArgs e)
{
    NavigationService.GoBack();
}

Podsumowanie

W tym odcinku nauczyłeś się odczytywać i zapisywać ustawienia w aplikacji. W kolejnym odcinku dowiesz się, jak szyfrować i deszyfrować poufne dane, takie jak: hasła, łańcuch połączeń i PIN w aplikacji na Windows Phone, używając Data Protection API (DPAPI).