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

时间:2012-12-30 11:40:32

标签: c# windows-8 microsoft-metro

我正在尝试将复选框(已选中/未选中)的状态保存到ApplicationData的LocalSettings for 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;

    }

就像我已经说过的那样,我已经尝试了几种方法来解决这个问题,但是他们都没有设法实际保存两个状态,只有其中一个(我希望你们中的一些人可能知道为什么,因为我“此刻如此迷失”。

出于某种原因,即使取消选中该复选框,当我调试“已检查”代码时也会被触发。

2 个答案:

答案 0 :(得分:2)

初始代码的问题在于您正在检查您的条件中的不同内容。您正在检查您存储的设置是否存在,然后是否选中该复选框。您目前正在做的是获取设置值(如果存在)。在加载时尝试以下操作。

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;
} 

答案 1 :(得分:1)

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"];
}