System.Collections.Generic.KeyNotFoundException 在 Windows Phone

System.Collections.Generic.KeyNotFoundException in Windows Phone

我遇到了以下代码的问题:

string name = (string)PhoneApplicationService.Current.State["name"];
names.Add(name);
InitializeComponent();
List.ItemsSource = names;

作者:

string name = (string)PhoneApplicationService.Current.State["name"];

我收到错误消息:

An exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code

代码在 C# 中。 我尝试使用其他页面的 Variabel。 如何查询应用程序跳转到其他页面的变量是否为"Not found"? 我该如何解决问题?

如果想在读取之前知道key是否存在,可以使用ContainsKey方法:

if (PhoneApplicationService.Current.State.ContainsKey("name"))
{
    string name = (string)PhoneApplicationService.Current.State["name"];
    names.Add(name);
    InitializeComponent();
    List.ItemsSource = names;
}
else
{
    // Whatever
}

此外,您似乎想在找不到密钥时导航到另一个页面。对 InitializeComponent 的调用表明您正在执行页面构造函数中的代码。如果您尝试使用构造函数中的 NavigationService,您将遇到 NullReferenceException。将代码移至 Loaded 事件,或覆盖 OnNavigatedTo 方法。