简体   繁体   English

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

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

I get a such exception: 我得到这样的异常:

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

I have a property in viewModel: 我在viewModel中有一个属性:

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

However, after I cleared FooStorage and trying to add new item: 但是,在清除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
    }
}

I've got an above exception. 我有一个例外。

When I call a method LoadData() at the first time, it all works okay. 当我第一次调用LoadData()方法时,一切正常。 Then if I call a method LoadData() at the second time, then I get a such exception. 然后,如果我第二次调用方法LoadData(),则会收到此类异常。

Have anybody met a such exception? 有人遇到过这样的例外吗? The most interesting thing that I cannot reproduce this exception in a test project. 我无法在测试项目中重现此异常的最有趣的事情。

StackTrace: 堆栈跟踪:

System.ArgumentOutOfRangeException was unhandled HResult=-2146233086 Message=Specified argument was out of the range of valid values. 未处理System.ArgumentOutOfRangeException HResult = -2146233086消息=指定的参数不在有效值范围内。 Parameter name: index ParamName=index Source=PresentationCore 参数名称: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.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 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.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(No 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 tifyCollectionChangedEventArgs args) at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Collections.ObjectModel.ObservableCollection 1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection 1.InsertItem(Int32 index, T item) at 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) 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 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(任务任务) 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, ContextCallba -)从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 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.Su 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) bclassWndProc(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, 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回调, 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: 对象状态,位于System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔值保持同步Ctx)位于System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态)。 ThreadHelper.ThreadStart()InnerException:

Update: 更新:

I am adding new TreeViewItem's from FooStorage to different TreeView placed inside of HeaderTemplate of DataGridTextBoxColumn . 我将新的TreeViewItem'sFooStorage添加到放置在DataGridTextBoxColumn的HeaderTemplate内的其他TreeView中。 So when user clicks at Header1 of DataGridTextBoxColumn2 , then TreeView of Header1 is populated by FooStorage from viewModel. 因此,当用户点击在Header1DataGridTextBoxColumn2 ,然后TreeViewHeader1是由填充FooStorage从视图模型。 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. 用户在点击时Header2DataGridTextBoxColumn2 ,然后TreeViewHeader2应通过填充FooStorage从视图模型,但是当我Clear()Add()新项目FooStorage ,然后我有一个以上的异常。

Just would like to say that passing UI Element TreeViewItem to ViewModel is a bad practice. 只是想说将UI元素TreeViewItem传递给ViewModel是一种不好的做法。 So maybe adding new TreeViewItem which is then used in different places was my problem. 所以也许添加新的TreeViewItem然后在不同的地方使用是我的问题。

As @Sinatr said: 正如@Sinatr所说:

You should not use TreeViewItem directly in ViewModel. 您不应直接在ViewModel中使用TreeViewItem。 Moreover framework elements (including TreeViewItem) can have only one parent at a time. 此外,框架元素(包括TreeViewItem)一次只能具有一个父级。 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). 也许添加新的TreeViewItem,然后在不同的地方使用是您的问题(如果需要,请cba检查源代码,根本就不要这样做)。 Rather use TreeViewItemViewModel (call it shorter, eg ItemViewModel). 而是使用TreeViewItemViewModel(简称它,例如ItemViewModel)。

Patrick Hofman gave me advice to disable that section in the UI and after I disabled it, then there was no problems. 帕特里克·霍夫曼(Patrick Hofman)为我提供了在UI中禁用该部分的建议,并且在禁用它之后,就没有问题了。

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! 而且ObservableCollection<T>无罪! Sorry, ObservableCollection<T> . 抱歉, ObservableCollection<T>

Now I am learning about TreeView by Josh Smith . 现在,我正在学习Josh Smith的TreeView

暂无
暂无

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

相关问题 指定的参数超出了有效值的范围。参数名称:值 - Specified argument was out of the range of valid values.Parameter name: value TimeSpan.FromSeconds 给出指定参数的错误超出有效值范围。参数名称:间隔 - TimeSpan.FromSeconds gives error of Specified argument was out of the range of valid values.Parameter name: Interval 指定的参数超出有效值范围。 参数名称索引。 由ObservableCollection.Add()方法抛出 - Specified argument was out of the range of valid values. parameter name index. thrown by ObservableCollection.Add() method 异常:指定的参数超出有效值的范围。 (参数“索引”) - Exception: Specified argument was out of the range of valid values. (Parameter 'index') 重现异常:指定的参数超出有效值范围。 参数名称:索引 - Reproduce exception: Specified argument was out of the range of valid values. Parameter name: index 错误指定的参数超出了有效值的范围。 参数名称:DataGridview Row Data Bound 中的索引 - Error Specified argument was out of the range of valid values. Parameter name: index in DataGridview Row Data Bound 指定的参数超出了有效值的范围。 参数名称:值 - Specified argument was out of the range of valid values. Parameter name: value System.ArgumentOutOfRangeException: &#39;指定的参数超出了有效值的范围。 参数名称:asp.net中的index&#39; - System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index' in asp.net 指定的参数超出有效值范围。 参数名称:动态生成的控件上的索引 - Specified argument was out of the range of valid values. Parameter name: index on dynamically generated Control 指定的参数超出有效值范围。 参数名称:大小 - Specified argument was out of the range of valid values. Parameter name: size
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM