简体   繁体   English

WP7中的IsolatedStorageSettings中的参数异常

[英]Argument exception in IsolatedStorageSettings in WP7

In following code, I am getting ArgumentException . 在下面的代码中,我正在获取ArgumentException This code checks if a key is set in IsolatedStorageSetting . 此代码检查是否在IsolatedStorageSetting设置了key If it is not there , then it is created. 如果不存在,则创建它。 At this point the exception is happening with message- value does not fall within the expected range . 此时,发生异常,消息value does not fall within the expected range What wrong I am doing ? 我在做什么错?

 protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

         var settings = IsolatedStorageSettings.ApplicationSettings;

        if (settings.Contains("bm"))
        {
            string k = (string) settings["bm"];
            if (k == "1")
            {
                cb1.IsChecked = true;
            }
            else
            {
                cb1.IsChecked = false;
            }
        }
        else
        {
            cb1.IsChecked=true;
            settings.Add("bm","1"); //exception occurs here
            settings.Save();
         }
}

As we can see in MSDN 正如我们在MSDN中看到的

ArgumentException occurs when ArgumentException发生在

key already exists in the dictionary. 字典中已存在该键。

So, I can see two problems: 因此,我可以看到两个问题:

  • Somewhere in the parallel thread the key "bm" is beeng saved to settings. 在并行线程中的某个位置,键“ bm”被保存到设置中。
  • Keys are different. 键是不同的。 "ь" and "b" are different letters, but they looks similar. “ь”和“ b”是不同的字母,但是看起来相似。

Try to define one constant string: 尝试定义一个常量字符串:

private const string BM_KEY = "bm";

and use it every time you access to settings. 并在您每次访问设置时使用它。

   if (settings.Contains(BM_KEY))
        {
            string k = (string) settings[BM_KEY];
            if (k == "1")
            {
                cb1.IsChecked = true;
            }
            else
            {
                cb1.IsChecked = false;
            }
        }
        else
        {
            cb1.IsChecked=true;
            settings.Add(BM_KEY,"1"); //exception occurs here
            settings.Save();
        }

to be sure, that you use the same key every time. 确保您每次都使用相同的密钥。

Or try to remove the already existing key (example "lastBranoCalled") ;) 或者尝试删除现有的键(例如“ lastBranoCalled”);)

if (IsolatedStorageSettings.ApplicationSettings.Remove("lastBranoCalled"))
                    IsolatedStorageSettings.ApplicationSettings.Add("lastBranoCalled", this.Panorama.SelectedIndex.ToString());
                else MessageBox.Show("Error");
            else IsolatedStorageSettings.ApplicationSettings.Add("lastBranoCalled", this.Panorama.SelectedIndex.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM