C# UWP保持ToggleSwitch.IsOn状态
这是我第一次尝试保存应用程序设置:toggleSwitch更改应用程序主题,然后将其存储在ApplicationDataContainer中迄今为止一切正常:当用户使用切换更改主题时,应用程序重新启动时将应用该切换到目前为止还很糟糕:toggleSwitch处于永久的IsOn=“True”模式,即使在XAML中没有提到它。因此,主题会在第二次重新启动时恢复到其原始状态。我应该实现什么才能使切换保持在所需的用户位置 XAMLC# UWP保持ToggleSwitch.IsOn状态,c#,windows,uwp,toggleswitch,C#,Windows,Uwp,Toggleswitch,这是我第一次尝试保存应用程序设置:toggleSwitch更改应用程序主题,然后将其存储在ApplicationDataContainer中迄今为止一切正常:当用户使用切换更改主题时,应用程序重新启动时将应用该切换到目前为止还很糟糕:toggleSwitch处于永久的IsOn=“True”模式,即使在XAML中没有提到它。因此,主题会在第二次重新启动时恢复到其原始状态。我应该实现什么才能使切换保持在所需的用户位置 XAML 在ApplyUserSettings方法中的else条件之后,您错过了花
在
ApplyUserSettings
方法中的else条件之后,您错过了花括号{}
。您所说的“toggleSwitch处于永久IsOn=“True”模式”是什么意思?另外,为什么不使用LocalSettings作为开/关值呢?似乎非常适合这个目的?您还可以使用绑定使其更简单。谢谢您,tao@Romasz开关永久关闭(tao的输入解决了这一问题)。我无法想象你的提议。请给我举个例子,使用LocalSettings作为开/关值,或者使用绑定,好吗?@M.forge互联网上已经有很多很好的教程和示例。看看谷歌。
<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>
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) { }
}}}