How to save my application settings?

Am I having trouble saving my application settings? I am creating a universal application for Windows 10, and I have a slider whose value I want to keep.

I use this code to save it:

private void musicVolume_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
    {
        ApplicationDataContainer AppSettings = ApplicationData.Current.LocalSettings;
        AppSettings.Values["musicV"] = musicVolume.Value;
    }

And in the constuctor of the page, I have the following lines of code:

ApplicationDataContainer AppSettings = ApplicationData.Current.LocalSettings;

        if (AppSettings.Values.ContainsKey("musicV"))
        {
            musicVolume.Value = Convert.ToDouble(AppSettings.Values["musicV"]);
        }

It should show a new value when I go to this page, but it’s not, it always shows the last one by default. Why does it not work and how to make it work?

PS: sorry for my bad english ...

+4
source share
3 answers

musicVolume.Value , . - .

, add:

Loaded += Page_Loaded;

:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    ApplicationDataContainer AppSettings = ApplicationData.Current.LocalSettings;

    if (AppSettings.Values.ContainsKey("musicV"))
    {
        musicVolume.Value = (double)AppSettings.Values["musicV"];
    }
}
+6

"SettingsManager", : fooobar.com/questions/1616178/...

- . ( .)

+1

OnNavigatedFrom:

 protected override void OnNavigatedFrom(NavigationEventArgs e)
 {
    ApplicationDataContainer AppSettings = ApplicationData.Current.LocalSettings;
    AppSettings.Values["musicV"] = musicVolume.Value;
 }

Now it saves the settings when you leave the page, and it works. I still don't understand why the method from my answer didn't work. Obviously, there is a problem with the ValueChanged event.

@nhuau: your solution looks good, but I am starting and don’t understand how to apply it to my problem. But I will remember this and in the future I will return to it.

+1
source

Source: https://habr.com/ru/post/1618279/


All Articles