繁体   English   中英

将新项目添加到ObservableCollection时,“指定的参数超出有效值范围。参数名称:索引” <T>

[英]“Specified argument was out of the range of valid values.Parameter name: index” when adding new item to ObservableCollection<T>

我得到这样的异常:

'FooStorageStorage.Add(new TreeViewItem(){Header = i.ToString()})引发了类型'System.ArgumentOutOfRangeException'的异常:“指定的参数超出有效值范围。\\ r \\ n参数名称:index ”

我在viewModel中有一个属性:

private ObservableCollection<TreeViewItem> fooStorage=new ObservableCollection<TreeViewItem>();
public ObservableCollection<TreeViewItem> FooStorage
{
   get { return facetStorage; }
   set { facetStorage = value; }
}

但是,在清除FooStorage并尝试添加新项目之后:

private void LoadData()
{
    if (FooStorage.Count > 0)
    {
       FooStorage.Clear();
    }
    for (int k = 0; k < lengthOfColl; k++)            
    {
       FooStorage.Add(new TreeViewItem() { Header=k.ToString()});//here is exception
    }
}

我有一个例外。

当我第一次调用LoadData()方法时,一切正常。 然后,如果我第二次调用方法LoadData(),则会收到此类异常。

有人遇到过这样的例外吗? 我无法在测试项目中重现此异常的最有趣的事情。

堆栈跟踪:

未处理System.ArgumentOutOfRangeException HResult = -2146233086消息=指定的参数不在有效值范围内。 参数名称:index ParamName = index Source = PresentationCore
StackTrace:位于System.Windows.Controls.UIElementCollection.InsertInternal(Int32索引,UIElement元素)位于System.Windows.Media.VisualCollection.Insert(Int32索引,可视视觉),位于System.Windows.Controls.Panel.AddChildren(GeneratorPosition pos, System.Windows.Controls.Panel.OnItemsChangedInternal(对象发件人,ItemsChangedEventArgs args)处的Int32 itemCount),System.Windows.Controls.ItemContainerGenerator.OnItemAdded(对象项,System.Windows.Controls.Panel.OnItemsChanged(对象发件人,ItemsChangedEventArgs args)处,在System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object sender,NotifyCollectionChangedEventArgs args)处System.Windows.WeakEventManager.ListenerList 1.DeliverEvent(Object sender, EventArgs e, Type managerType) at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args) at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e) at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Controls.ItemCollection.OnViewCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Windows.WeakEventManager.ListenerList 1.DeliverEvent(Object sender, EventArgs e, Type managerType) at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args) at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e) at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Controls.ItemCollection.OnViewCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Windows.WeakEventManager.ListenerList 1.System.Windows.WeakEventManager.DeliverEvent(对象发件人,EventArgs args)在System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(对象发件人,NotifyCollectionChangedEventArgs args)的DeliverEvent(对象发件人,EventArgs e,类型managerType)在System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args,Int32 AdjustedOldIndex,Int32 AdjustedNewIndex)在System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(System.Windows.Data.ListCollectionView.ProcessCollectionChanged(No System.Windows.Data.CollectionView.OnCollectionChanged(对象发件人,NotifyCollectionChangedEventArgs args)位于System.Collections.ObjectModel.ObservableCollection 1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection 1.InsertItem(Int32 index) System.Collections.ObjectModel.Collection上的1.Add(T item) at ModuleA.ViewModel.PersonControlViewModel.LoadData(IPerson person) in D:\\WPF\\...\\ViewModel\\PersonControlViewModel.cs:line 110 at Prism.Commands.DelegateCommand 1. Prism.Commands.DelegateCommandBase的<<> c__DisplayClass1_0。<。ctor> b__0(Object o).Prism.Commands.DelegateCommandBase.d__14.MoveNext(>的c__DisplayClass5_0。<。ctor> b__0(Object arg) )-从先前抛出异常的位置开始的堆栈跟踪--在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task)的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) -)从System.Runtime.CompilerServices.AsyncMethodBuilderCore。<> c.b__6_0(对象状态)处-从抛出异常的先前位置开始跟踪堆栈结束System.Windows.Thread.ExceptionWrapper.TryCatchWhen(对象源,委托回调,对象args,Int32 numArgs,委托catchHandler)在System.Windows.System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调,对象args,Int32 numArgs)。 System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(对象状态)处于System.Windows.Threading.ExecutionContext.RunInternal(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔型saveSyncCtx)位于System.Windows.Thread.System.Windows.Threading.DispatcherOperation.InvokeImpl() System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallba)中的(ExecutionContext executeContext,ContextCallback回调,对象状态,布尔类型saveSyncCtx) ck回调,对象状态),位于MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executeContext,ContextCallback回调,对象状态),位于System.Windows.Threading.DispatcherOperation.Invoke(),位于系统。 .Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,布尔值和已处理)在MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,IntPtr lParam) System.Windows.Threading.ExceptionWrapper.InternalRealCall处的.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Delegate callback,Object args,Int32 numArgs)(Object source,Delegate callback,Object args, Int32 numArgs,在System.Windows.Threading.Dispatcher.LegacyInvokeImpl(Delegate catchHandler)处(MS.Win32.HwndSubclass.Su上的DispatcherPriority优先级,TimeSpan超时,委托方法,对象args,Int32 numArgs) System.Windows.Thread.Dispatcher.PushFrameImpl(DispatcherFrame框架)处的System.Windows。 (位于System.Windows.Application.RunDispatcher(DispatcherFrame frame)在System.Windows.Application.RunInternal(Window window)在System.Windows.Application.Run(Window window)在System.Windows.Application.Run()在D:\\ WPF ... \\ Src \\ PrototypeBootstrapper \\ obj \\ Debug \\ App.g.cs中的PrototypeBootstrapper.App.Main()处,在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,系统中的String [] args)处位于Line 0 .AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()在System.Threading.ThreadHelper.ThreadStart_Context(Object state)在System.Threading.ExecutionContext.RunInternal(ExecutionContext) executionContext,ContextCallback回调, 对象状态,位于System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔值保持同步Ctx)位于System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态)。 ThreadHelper.ThreadStart()InnerException:

更新:

我将新的TreeViewItem'sFooStorage添加到放置在DataGridTextBoxColumn的HeaderTemplate内的其他TreeView中。 因此,当用户点击在Header1DataGridTextBoxColumn2 ,然后TreeViewHeader1是由填充FooStorage从视图模型。 好。 用户在点击时Header2DataGridTextBoxColumn2 ,然后TreeViewHeader2应通过填充FooStorage从视图模型,但是当我Clear()Add()新项目FooStorage ,然后我有一个以上的异常。

只是想说将UI元素TreeViewItem传递给ViewModel是一种不好的做法。 所以也许添加新的TreeViewItem然后在不同的地方使用是我的问题。

正如@Sinatr所说:

您不应直接在ViewModel中使用TreeViewItem。 此外,框架元素(包括TreeViewItem)一次只能具有一个父级。 也许添加新的TreeViewItem,然后在不同的地方使用是您的问题(如果需要,请cba检查源代码,根本就不要这样做)。 而是使用TreeViewItemViewModel(简称它,例如ItemViewModel)。

帕特里克·霍夫曼(Patrick Hofman)为我提供了在UI中禁用该部分的建议,并且在禁用它之后,就没有问题了。

因此,我得出的结论是,我遇到了使用错误做法的后果,并受到了惩罚。 避免不良做法。 而且ObservableCollection<T>无罪! 抱歉, ObservableCollection<T>

现在,我正在学习Josh Smith的TreeView

暂无
暂无

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

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