UWP维护ToggleSwitch.IsOn状态

时间:2016-10-27 20:28:51

标签: c# windows uwp toggleswitch

这是我第一次尝试保存应用设置:toggleSwitch更改应用主题,然后将其存储在ApplicationDataContainer中。 到目前为止一直很好:当用户使用切换更改主题时,它会在应用重新启动时应用。 到目前为止很糟糕: toggleSwitch处于永久的IsOn =“True”模式,即使在XAML中没有提及它。因此,主题在第二次重启时恢复到原始状态。我应该实现什么才能使切换保持在所需的用户位置?

XAML

<Page
    x:Class="App3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App3"   
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ToggleSwitch OffContent="Light"
                      OnContent="Dark"
                      x:Name="toggleSwitch"
                      Header="ToggleSwitch"
                      Toggled="toggleSwitch_Toggled"/>
    </Grid>
</Page>

CS

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

namespace App3
{
public sealed partial class MainPage : Page
{ ApplicationDataContainer localSettings = null;
  ApplicationDataContainer local = null;
  const string toggleSwitch_Toggle = "example";

    public MainPage()
    {   ApplyUserSettings();
        this.InitializeComponent();
        localSettings = ApplicationData.Current.LocalSettings;
        local = ApplicationData.Current.LocalSettings; }

    private async void toggleSwitch_Toggled(object sender, RoutedEventArgs e)
    {   StorageFolder local = ApplicationData.Current.LocalFolder;
        var dataFolder = await local.CreateFolderAsync("Data Folder", CreationCollisionOption.OpenIfExists);
        var file = await dataFolder.CreateFileAsync("SwitchBWThemeMode.txt", CreationCollisionOption.ReplaceExisting);
        if (toggleSwitch.IsOn)
        {   await FileIO.WriteTextAsync(file, "on");   }
        else await FileIO.WriteTextAsync(file, "off");   }

    private async void ApplyUserSettings()
    {   try
        {   StorageFolder local = ApplicationData.Current.LocalFolder;
            var dataFolder = await local.GetFolderAsync("Data Folder");
            var file = await dataFolder.GetFileAsync("SwitchBWThemeMode.txt");
            String SwitchBWThemeMode = await FileIO.ReadTextAsync(file);

            if (SwitchBWThemeMode == "on")
            {   RequestedTheme = ElementTheme.Dark;
                toggleSwitch.IsOn = true;    }
            else RequestedTheme = ElementTheme.Light;
            toggleSwitch.IsOn = false;
        }
        catch (Exception) { }
}}}

0 个答案:

没有答案