如何保存应用程序设置?

时间:2016-11-01 15:53:26

标签: c# .net uwp .net-core windows-10-iot-core

我们有Windows IoT核心的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";
    }
}

1 个答案:

答案 0 :(得分:3)

如果您想在本地存储您的设置,您可以将它们存储为单个项目或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"];
}