我正在尝试创建和隔离存储设置,用户可以根据用户设置页面中切换开关的状态打开或关闭声音或振动警报(或两者)。我正在使用 mvvm 框架,需要在 MainViewModel 类中引用 Setting 类。我意识到我需要插入一个 if 语句作为该过程的一部分,但遇到了困难。
设置.xaml
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<toolbox:ToggleSwitch Name="MobileSound" Header="Sound"></toolbox:ToggleSwitch>
<toolbox:ToggleSwitch Name="MobileVibrate" Header="Vibrate" Margin="6,119,6,371"></toolbox:ToggleSwitch>
<Slider Height="84" HorizontalAlignment="Left" Margin="12,310,0,0" Name="slider1" VerticalAlignment="Top" Width="418" Value="1" Minimum="1" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="12,274,0,0" Name="Difficulty" Text="Refresh Timer" VerticalAlignment="Top" Width="135" />
</Grid>
设置.cs
using System;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;
namespace MobileApplicationSample
{
/// <summary>
/// Description for Setting.
/// </summary>
public partial class Setting : PhoneApplicationPage
{
// Constructor
public Setting()
{
InitializeComponent();
settings = IsolatedStorageSettings.ApplicationSettings;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
System.Diagnostics.Debug.WriteLine("into the app");
try
{
System.Diagnostics.Debug.WriteLine("Retrieving values");
MobileSound.IsChecked = (bool)settings["sound"];
MobileVibrate.IsChecked = (bool)settings["vibrate"];
slider1.Value = (Int16)settings["diff"];
}
catch (KeyNotFoundException)
{
System.Diagnostics.Debug.WriteLine("First Time using the app");
settings.Add("sound", false);
settings.Add("vibrate", false);
settings.Add("diff", 1);
settings.Save();
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Exiting, so save now");
settings["vibrate"] = MobileVibrate.IsChecked;
settings["sound"] = MobileSound.IsChecked;
settings["diff"] = (Int16)slider1.Value;
settings.Save();
}
public IsolatedStorageSettings settings { get; set; }
}
}