System.Collections.Generic.KeyNotFoundException in Windows Phone

房东的猫 提交于 2021-01-27 05:27:35

问题


i got a Problem with this following Code:

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

by:

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

i got the error message:

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

The Code is in C#. I try to use an Variabel from the othe Page. How can i ask if the variable is "Not found" that the app jump to the other Page? How can i solve the Problem?


回答1:


If you want to know whether the key exists before reading it, you can use the ContainsKey method:

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

Also, you seem to want to navigate to another page when the key isn't found. The call to InitializeComponent shows that you're executing the code in the page constructor. If you try to use the NavigationService from the constructor, you will have a NullReferenceException. Move the code to the Loaded event, or override the OnNavigatedTo method.



来源:https://stackoverflow.com/questions/28146947/system-collections-generic-keynotfoundexception-in-windows-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!