保存复选框状态到localsettings, windows 8

本文关键字:windows localsettings 复选框 状态 保存 | 更新日期: 2023-09-27 17:49:52

我目前正试图保存一个复选框的状态(选中/未选中)到ApplicationData的LocalSettings为我的Modern UI应用程序。我一直在解决这个问题在过去的6-7小时,尝试了大量不同的方法,但我相信我完全迷失在我自己的代码现在。我的代码到目前为止:

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        if (localSettings.Values.ContainsKey("isFirstChecked") == false || cbFirst.IsChecked == false)
        {
            cbFirst.IsChecked = false;
            test.Text = "UnChecked";
        }
        else 
        {
            cbFirst.IsChecked = true;
            test.Text = "Checked";
        }
    }
    private void cbFirst_Checked(object sender, RoutedEventArgs e)
    {
        test.Text = "Checked";
        localSettings.Values["isFirstChecked"] = cbFirst.IsChecked = true;
    }
    private void cbFirst_Unchecked(object sender, RoutedEventArgs e)
    {
        test.Text = "UnChecked";
        var test2 = localSettings.Values["isFirstChecked"] = cbFirst.IsChecked = false;
    }

就像我已经说过的,我已经尝试了几种方法来解决这个问题,但没有一种方法能够真正拯救两个州,只有一个州(我希望你们中的一些人可能知道为什么,因为我现在很失落)。

由于某些原因,当我调试"Checked"代码时,即使复选框未选中也会被触发

保存复选框状态到localsettings, windows 8

初始代码的问题是您在条件中检查不同的东西。您将检查已存储的设置是否存在,然后检查复选框是否被选中。您目前没有做的是获取设定值(如果它存在)。在加载时尝试以下操作。

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    bool valueFromSettings = false;
    if (!localSettings.Values.ContainsKey("isFirstChecked"))
    {
        // if the setting doesn't exist, probably wise to create it here.
        // setting the default to "false", but you can change to true if that makes more sense.
        localSettings.Values.Add("isFirstChecked", false);
    }
    else
    {
        // read the value of the setting here.  
        // If we just created it, it should default to false (see above)
        valueFromSetting = ((bool)localSettings.Values["isFirstChecked"]);
    }
    if(valueFromSettings)
    {
        cbFirst.IsChecked = true;
        test.Text = "Checked";
    }
    else 
    {
        cbFirst.IsChecked = false;
        test.Text = "UnChecked";
    }
}

然后,您可以使用您之前定义的处理程序(但请注意细微的变化—您不需要检查复选框的值,但可以直接分配设置。)

private void cbFirst_Checked(object sender, RoutedEventArgs e)
{
    test.Text = "Checked";
    localSettings.Values["isFirstChecked"] = true;
}
private void cbFirst_Unchecked(object sender, RoutedEventArgs e)
{
    test.Text = "UnChecked";
    localSettings.Values["isFirstChecked"] = false;
} 
private void cbFirstCheckedChanged(object sender, EventArgs e)
{
    var checkBox = serder as CheckBox;
    if (checkBox == null) return;
    test.Text = checkBox.IsChecked ? "Checked" : "UnChecked";
    localSettings.Values["isFirstChecked"] = cbFirst.IsChecked
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    checkBox.IsChecked = localSettings.Values["isFirstChecked"];
}