MessageBox.Show(item.name)
,它将显示所有对象的名称。没有值为空,我检查了三次。以下是我创建按钮的方式:
ItemList[] items = JsonConvert.DeserializeObject<ItemList[]>(jsonString);
Dispatcher.BeginInvoke(new Action(() =>
{
foreach (ItemList item in items)
{
Button ItemName = new Button();
//defining properties of the button, like width, etc..
ItemName.Content = item.title;
ItemName.Name = item.id;
//Will add Click event.
ItemPanel.Children.Add(ItemName);
}
}));
尝试创建时,我收到了TargetInvocationException:
[System.Reflection.TargetInvocationException {System.Reflection.TargetInvocationException: 远程调用的目标发生异常。 ---> System.NullReferenceException: 对象引用未设置为对象的实例。
为什么会这样?谜团。我仅仅尝试创建按钮对象并将其添加到我的StackPanel中而不做其他任何事情,错误仍然存在。
我做错了什么?如何摆脱这个问题?我已经在另一个应用程序中创建了像那样的动态元素,那个应用程序正常工作。
创建按钮的函数在从api获取JSON的函数末尾调用HTTP请求。该HTTP请求函数在OnNavigatedTo方法中调用(是的,这很奇怪,但这是我找到的唯一一种自动调用函数的方法,使用来自OnNavigatedTo方法的变量。我在其他页面上这样做过,并且可以运行(虽然它不是创建按钮,只是修改现有的文本块)。
下面是完整的错误信息:
System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. --->
System.NullReferenceException: Object reference not set to an instance of an object.
at CubbyHole_Mobile.BrowseFiles.<>c__DisplayClass1.b__0()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
以下是堆栈跟踪信息:
CubbyHole Mobile.DLL!CubbyHole_Mobile.App.Application_UnhandledException(object sender, System.Windows.ApplicationUnhandledExceptionEventArgs e) Ligne 100 C#
System.Windows.ni.dll!MS.Internal.Error.CallApplicationUEHandler(System.Exception e) Inconnu
System.Windows.ni.dll!MS.Internal.Error.IsNonRecoverableUserException(System.Exception ex, out uint xresultValue) Inconnu
System.Windows.ni.dll!System.Windows.Threading.DispatcherOperation.Invoke() Inconnu
System.Windows.ni.dll!System.Windows.Threading.Dispatcher.Dispatch(System.Windows.Threading.DispatcherPriority priority) Inconnu
System.Windows.ni.dll!System.Windows.Threading.Dispatcher.OnInvoke(object context) Inconnu
System.Windows.ni.dll!System.Windows.Hosting.CallbackCookie.Invoke(object[] args) Inconnu
System.Windows.RuntimeHost.ni.dll!System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(System.IntPtr pHandle, int nParamCount, System.Windows.Hosting.NativeMethods.ScriptParam* pParams, System.Windows.Hosting.NativeMethods.ScriptParam* pResult) Inconnu
抱歉,这是法语代码,但应该可读。
此外,当尝试将新创建的项添加到现有的 StackPanel 时,会引发错误,但不会停留在该行。它转到 app.xaml.cs 中的 UnhandledException 方法,并使用 Debugger.Break(); 停止(就像我在处理此问题时遇到的几乎所有错误一样)。
ItemPanel
是否为空?或者由于某些原因是ItemPanel.Children
为空?您应该能够在那里设置一个断点,确定哪个值为空,或者至少哪一行是有问题的行。 - Kevin DiTraglia