如何保存应用程序设置?

How to save application settings?

我们有一个用于 Windows IoT Core 的 UWP,我们需要保存一些设置,但即使应用程序停止或 IoT 设备重新启动,这些设置也必须存在。

我的代码如下,当应用程序打开时它工作得很好,如果我在 XAML 页面之间切换,但是当应用程序停止时它不起作用,就像变量从未存在过。

static class Global
{
    public static Windows.Storage.ApplicationDataContainer localSettings { get; set; }
    public static Windows.Storage.StorageFolder localFolder { get; set; }
}

private void Btn_Inciar_Config_Click(object sender, RoutedEventArgs e)
{
    if (TxtDeviceKey.Text != String.Empty || TxtDeviceName.Text != String.Empty || Txt_Humedad_Config.Text != String.Empty || Txt_Intervalo_Config.Text != String.Empty || Txt_Temperatura_Ambiente_Config.Text != String.Empty || Txt_Temperaura_Config.Text != String.Empty)
    {
        Windows.Storage.ApplicationDataCompositeValue composite =
        new Windows.Storage.ApplicationDataCompositeValue();
        composite["GlobalDeviceKey"] = TxtDeviceKey.Text;
        composite["GlobalDeviceName"] = TxtDeviceName.Text;
        composite["GlobalTemperature"] = Txt_Temperaura_Config.Text;
        composite["GlobalHumidity"] = Txt_Humedad_Config.Text;
        composite["GlobalTemperatureRoom"] = Txt_Temperatura_Ambiente_Config.Text;
        composite["GlobalInterval"] = Txt_Intervalo_Config.Text;

        localSettings.Values["ConfigDevice"] = composite;
        Lbl_Error.Text = "";
        Frame.Navigate(typeof(MainPage));
    }
    else
    {
        Lbl_Error.Text = "Ingrese todos los campos de configuracion";
    }
}

如果您想在本地存储您的设置,您可以将它们存储为单个项目或像您一样存储为 ApplicationDataCompositeValue(将所有值保存为一个实体)。只需将复合(或单个项目)放入 ApplicationData.Current.LocalSettings 容器中。在一小段代码下面,您可以简单地复制粘贴到一个空的应用程序中并附加到 2 个按钮来试用。

private void SaveClicked(object sender, RoutedEventArgs e)
{
    Windows.Storage.ApplicationDataCompositeValue composite =
        new Windows.Storage.ApplicationDataCompositeValue();
    composite["GlobalDeviceKey"] = "Key";
    composite["GlobalDeviceName"] = "Name";
    ApplicationData.Current.LocalSettings.Values["ConfigDevice"] = composite;
}

private void LoadClicked(object sender, RoutedEventArgs e)
{
    Windows.Storage.ApplicationDataCompositeValue composite =
        (ApplicationDataCompositeValue) ApplicationData.Current.LocalSettings.Values["ConfigDevice"];
    var key = (string)composite["GlobalDeviceKey"];
}