“指定的参数超出有效值范围.参数名称:索引"当将新项目添加到ObservableCollection< T>时 [英] "Specified argument was out of the range of valid values.Parameter name: index" when adding new item to ObservableCollection<T>

查看:165
本文介绍了“指定的参数超出有效值范围.参数名称:索引"当将新项目添加到ObservableCollection< T>时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的异常:

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

'FooStorageStorage.Add(new TreeViewItem() { Header=i.ToString()})' threw an exception of type 'System.ArgumentOutOfRangeException': "Specified argument was out of the range of valid values.\r\nParameter name: index"

我在viewModel中有一个属性:

I have a property in viewModel:

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

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

However, after I cleared FooStorage and trying to add new item:

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(),则会收到此类异常.

When I call a method LoadData() at the first time, it all works okay. Then if I call a method LoadData() at the second time, then I get a such exception.

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

Have anybody met a such exception? The most interesting thing that I cannot reproduce this exception in a test project.

StackTrace:

StackTrace:

未处理System.ArgumentOutOfRangeException HResult = -2146233086 Message =指定的参数超出有效值范围. 参数名称:index ParamName = index Source = PresentationCore
堆栈跟踪: 在System.Windows.Media.VisualCollection.Insert(Int32索引,视觉) 在System.Windows.Controls.UIElementCollection.InsertInternal(Int32 索引,UIElement元素) 在System.Windows.Controls.Panel.AddChildren(GeneratorPosition pos,Int32 itemCount) 在System.Windows.Controls.Panel.OnItemsChangedInternal(Object sender,ItemsChangedEventArgs args) 在System.Windows.Controls.Panel.OnItemsChanged(对象发送者,ItemsChangedEventArgs参数) 在System.Windows.Controls.ItemContainerGenerator.OnItemAdded(Object 项目,Int32索引) 在System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object 发送者,NotifyCollectionChangedEventArgs参数) 在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 发送者,EventArgs e,类型为managerType) 在System.Windows.WeakEventManager.DeliverEvent(对象发送者,EventArgs args) 在System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object 发送者,NotifyCollectionChangedEventArgs参数) 在System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) 在System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args,调整为Int32的OldIndex,调整为Int32的NewIndex) 在System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args) 在System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs参数) 在System.Collections.ObjectModel.ObservableCollection 1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection 1.InsertItem(Int32 索引,T项) 在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.<> c__DisplayClass1_0.< .ctor> b__0(Object o) 在Prism.Commands.DelegateCommandBase处.<> c__DisplayClass5_0.< .ctor> b__0(Object arg) 在Prism.Commands.DelegateCommandBase.d__14.MoveNext() ---从上一个引发异常的位置开始的堆栈结束跟踪--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task 任务) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task 任务) 在Prism.Commands.DelegateCommandBase.d__12.MoveNext() ---从上一个引发异常的位置开始的堆栈结束跟踪--- 在System.Runtime.CompilerServices.AsyncMethodBuilderCore中.<> c.b__6_0(Object 状态) 在System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate 回调,对象参数,Int32 numArgs) 在System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象源, 委托回调,对象args,Int32 numArgs,委托catchHandler) 在System.Windows.Threading.DispatcherOperation.InvokeImpl() 在System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object 状态) 在System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback回调,对象状态,布尔值 reserveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext executeContext,ContextCallback回调,对象状态,布尔值 reserveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态) 在MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext,ContextCallback回调,对象状态) 在System.Windows.Threading.DispatcherOperation.Invoke() 在System.Windows.Threading.Dispatcher.ProcessQueue() 在System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,布尔值和已处理) 在MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&处理) 在MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 在System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate 回调,对象参数,Int32 numArgs) 在System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象源, 委托回调,对象args,Int32 numArgs,委托catchHandler) 在System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority 优先级,TimeSpan超时,委托方法,对象参数,Int32 numArgs) 在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam) 在MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 在System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame 框架) 在System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架) 在System.Windows.Application.RunDispatcher(对象忽略) 在System.Windows.Application.RunInternal(Window窗口) 在System.Windows.Application.Run(窗口窗口) 在System.Windows.Application.Run() 在D:\ WPF ... \ Src \ PrototypeBootstrapper \ obj \ Debug \ App.g.cs:line 0中的PrototypeBootstrapper.App.Main()处 在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String []参数) 在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)中 在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在System.Threading.ThreadHelper.ThreadStart_Context(对象状态) 在System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback回调,对象状态,布尔值 reserveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext executeContext,ContextCallback回调,对象状态,布尔值 reserveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态) 在System.Threading.ThreadHelper.ThreadStart()处InnerException:

System.ArgumentOutOfRangeException was unhandled HResult=-2146233086 Message=Specified argument was out of the range of valid values. Parameter name: index ParamName=index Source=PresentationCore
StackTrace: at System.Windows.Media.VisualCollection.Insert(Int32 index, Visual visual) at System.Windows.Controls.UIElementCollection.InsertInternal(Int32 index, UIElement element) at System.Windows.Controls.Panel.AddChildren(GeneratorPosition pos, Int32 itemCount) at System.Windows.Controls.Panel.OnItemsChangedInternal(Object sender, ItemsChangedEventArgs args) at System.Windows.Controls.Panel.OnItemsChanged(Object sender, ItemsChangedEventArgs args) at System.Windows.Controls.ItemContainerGenerator.OnItemAdded(Object item, Int32 index) at System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Windows.WeakEventManager.ListenerList1.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.ListenerList1.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.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex) at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Collections.ObjectModel.ObservableCollection1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection1.Add(T item) at ModuleA.ViewModel.PersonControlViewModel.LoadData(IPerson person) in D:\WPF\...\ViewModel\PersonControlViewModel.cs:line 110 at Prism.Commands.DelegateCommand1.<>c__DisplayClass1_0.<.ctor>b__0(Object o) at Prism.Commands.DelegateCommandBase.<>c__DisplayClass5_0.<.ctor>b__0(Object arg) at Prism.Commands.DelegateCommandBase.d__14.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Prism.Commands.DelegateCommandBase.d__12.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.b__6_0(Object state) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at PrototypeBootstrapper.App.Main() in D:\WPF...\Src\PrototypeBootstrapper\obj\Debug\App.g.cs:line 0 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

更新:

我正在从FooStorage向位于DataGridTextBoxColumn的HeaderTemplate内的其他TreeView添加新的TreeViewItem's.因此,当用户单击DataGridTextBoxColumn2Header1时,Header1TreeView将由viewModel中的FooStorage填充.好的.当用户单击DataGridTextBoxColumn2Header2时,应从viewModel中的FooStorage填充Header2TreeView,但是当我Clear()Add()新项添加到FooStorage时,则我上面有一个例外.

I am adding new TreeViewItem's from FooStorage to different TreeView placed inside of HeaderTemplate of DataGridTextBoxColumn. So when user clicks at Header1 of DataGridTextBoxColumn2, then TreeView of Header1 is populated by FooStorage from viewModel. OK. The when user clicks at Header2 of DataGridTextBoxColumn2, then TreeView of Header2 should be populated by FooStorage from viewModel, however when I Clear() and Add() new items to FooStorage, then I've got an above exception.

推荐答案

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

Just would like to say that passing UI Element TreeViewItem to ViewModel is a bad practice. So maybe adding new TreeViewItem which is then used in different places was my problem.

正如@Sinatr所说:

As @Sinatr said:

您不应直接在ViewModel中使用TreeViewItem.而且 框架元素(包括TreeViewItem)只能有一个父对象 一次.也许添加新的TreeViewItem,然后将其用于 您的问题出在不同的地方(CBA会检查来源是否是 的情况下,根本就不要这样做).而是使用TreeViewItemViewModel(将其称为 较短,例如ItemViewModel).

You should not use TreeViewItem directly in ViewModel. Moreover framework elements (including TreeViewItem) can have only one parent at a time. Maybe adding new TreeViewItem which is then used in different places is your problem (cba to check sources if it's the case, simply don't do it). Rather use TreeViewItemViewModel (call it shorter, e.g. ItemViewModel).

帕特里克·霍夫曼(Patrick Hofman)给了我建议,以在用户界面中禁用该部分,然后在禁用它之后,就没有问题了.

Patrick Hofman gave me advice to disable that section in the UI and after I disabled it, then there was no problems.

因此,我得出的结论是,我已经遭受了不良习惯的后果,并受到了惩罚. 避免不良做法.而ObservableCollection<T>则无罪!抱歉,ObservableCollection<T>.

So I've concluded that I've met consequences of using bad practice and was punished. Avoid bad practices. And ObservableCollection<T> is not guilty! Sorry, ObservableCollection<T>.

现在我正在学习TreeView由乔什·史密斯(Josh Smith).

这篇关于“指定的参数超出有效值范围.参数名称:索引"当将新项目添加到ObservableCollection&lt; T&gt;时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆