我遇到以下代码问题:
string name = (string)PhoneApplicationService.Current.State["name"];
names.Add(name);
InitializeComponent();
List.ItemsSource = names;
by:
string name = (string)PhoneApplicationService.Current.State["name"];
我收到错误消息:
“System.Collections.Generic.KeyNotFoundException”类型的异常
发生在 mscorlib.ni.dll 中,但未在用户代码中处理
代码是 C# 语言。
我尝试使用其他页面中的变量。
如何询问应用程序跳转到其他页面的变量是否“未找到”?
我该如何解决这个问题?
如果你想在读取之前知道密钥是否存在,可以使用ContainsKey
method:
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
方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)