I get this exception: ...">

"The specified argument is out of range. Parameter name: index" when adding a new element to the ObservableCollection <T>

I get this exception:

'FooStorageStorage.Add (new TreeViewItem () {Header = i.ToString ()})' threw an exception of type "System.ArgumentOutOfRangeException": "The specified argument was out of range. \ R \ nParameter name: index"

I have a viewModel property:

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

However, after I cleared FooStorage and tried to add a 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 } } 

I have an exception.

When I call the LoadData () method for the first time, everything works fine. Then, if I call the LoadData () method a second time, then I get such an exception.

Has anyone met such an exception? The most interesting thing is that I can not reproduce this exception in a test project.

Stacktrace:

System.ArgumentOutOfRangeException error was unhandled. HResult = -2146233086 Message = The specified argument is out of range. Parameter Name: index ParamName = index Source = PresentationCore
Stack traces: in System.Windows.Media.VisualCollection.Insert (Int32 index, visual visual) in System.Windows.Controls.UIElementCollection.InsertInternal (Int32 index, UIElement) in System.Windows.Controls.Panel.AddChildren (GeneratorPosition pos , Int32 itemCount) in System.Windows.Controls.Panel.OnItemsChangedInternal (Sender Object, ItemsChangedEventArgs args) in System.Windows.Controls.Panel.OnItemsChanged (Object sender, ItemsChangedEventArgs args) in System.Windows.Controls.ItemConterOnItemConter item, index Int32) in System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged (Object sender, NotifyCollectionChangedEventArgs args) in 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, EventArgsWeE.Tel. (object sender, EventArgs arguments) in System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged (object sender, NotifyCollectionChangedEventArgs args) in System.Windows.Data.CollectionView.OnCollectionChanged (Notif yCollectionChangedEventArgs arg) in the System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex (NotifyCollectionChangedEventArgs args, Int32 adjustOldIndex, Int32 adjustNewIndex) in the System.Windows.Data.ListCollectionlectionCholg.olgolang , NotifyCollectionChangedEventArgs args) in System.Collections.ObjectModel.ObservableCollection 1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection 1.InsertItem (Int32 index, 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) in Prism.Commands.DelegateCommandBase. <> c__DisplayClass5_0. <.ctor> b__0 (Object Arg) in Prism.Commands.DelegateCommandBase.d__14.MoveNext () --- The end of the stack trace from the previous place where the exception was thrown --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Task task) in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Task task) in Prism.Commands.DelegateCommandBase.d__12.MoveNext () --- The end of the stack trace from the previous place where the exception was thrown --- in System.Runtime. CompilerServices.AsyncMethodBuilderCore. <> c.b__6_0 (Object state) in System.Windows.Threading.ExceptionWrapper.InternalRealCall (delegate callback, Object args, Int32 numArgs) in System.Windows.Threading.ExceptionWrapper.TryCatchWhen (object source, Delegate callback, Object arguments, Int32 numArgs, Delegate catchHandler) to System.Windows.Threading.DispatcherOperation.InvokeImpl () to System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext (state) in System.Threading.ExecutionContext.RunInternal (ExecutionContext executeContext executeContext executeContext , logical preserveSyncCtx) in System.Threading.ExecutionContext.Run (ExecutionContext executeContext, ContextCallback callback, object state, logical value there is preserveSyncCtx) in System.Threading.ExecutionContext.Run (ExecutionContext executeContext, ContextCallback callback, object state) in MS.Internal.CulturePreservingExecutionContext.Run (CulturePreservingExecutionContext executeContext, ContextCallback.Context.Data callback.Context.readback.Context.Reference. Invoke () in System.Windows.Threading.Dispatcher.ProcessQueue () in System.Windows.Threading.Dispatcher.WndProcHook (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean & processed) on MS.Win32.HwndWrapper (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean & processed) on MS.Win32.HwndSubclass.DispatcherCallbackOperation (Object o) in System.Windows.Threading.ExceptionWrapper.InternalRealCall (delegate, callback, Object32 System.Windows.Threading.E xceptionWrapper.TryCatchWhen (object source, Delegate callback, Object arguments, Int32 numArgs, Delegate catchHandler) in System.Windows.Threading.Dispatcher.LegacyInvokeImpl (DispatcherPriority priority, TimeSpan timeout, delegation method, object arguments, Int32 numArgs) .Win32.HwndSubclass.SubclassWndProc (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) in MS.Win32.UnsafeNativeMethods.DispatchMessage (MSG & msg) in System.Windows.Threading.Dispatcher.FrameFrameFrameFrameFrameFrameFrameFrameFrameFrame .Threading.Dispatcher.PushFrame in System.Windows.Application.RunDispatcher (Object ignore) in System.Windows.Application.RunInternal (window window) in System.Windows.Application.Run (window window) in System.Windows .Application.R un () in PrototypeBootstrapper.App.Main () in D: \ WPF ... \ Src \ PrototypeBootstrapper \ obj \ Debug \ App.g.cs: line 0 in System.AppDomain._nExecuteAssembly (assembly RuntimeAssembly, String [] args ) in System.AppDomain.ExecuteAssembly (String assemblyFile, Evidence assemblySecurity, String [] args) in Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly () in System.Threading.ThreadHelper.ThreadStart_Context (object state) in System.Threading.Exec. RunInternal (ExecutionContext executeContext, ContextCallback callback, object state, logical preserveSyncCtx) in System.Threading.ExecutionContext.Run (ExecutionContext executeContext, ContextCallback callback, object state, boolean preserveSyncCtx) in System.ThreadingContext.Execution about inverse challenge ContextCallback, state of the object) in System.Threading.ThreadHelper.ThreadStart () InnerException:

Update:

I am adding a new TreeViewItem's from FooStorage to another TreeView placed inside the HeaderTemplate DataGridTextBoxColumn . Therefore, when the user clicks < Header1 DataGridTextBoxColumn2 , then the TreeView from Header1 populated with FooStorage from viewModel. OK. When the user clicks on Header2 from DataGridTextBoxColumn2 , then TreeView of Header2 should be filled with FooStorage from viewModel, however, when I Clear() and Add() new elements in FooStorage , then I have an exception.

-1
source share
1 answer

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

As @Sinatr said:

You should not use TreeViewItem directly in the ViewModel. furthermore, structure elements (including TreeViewItem) can have only one parent at a time. Perhaps adding a new TreeViewItem, which is then used in different places, is your problem (cba to check sources, if this is the case, just don't do this). Rather, use a TreeViewItemViewModel (name it shorter, for example. ItemViewModel).

Patrick Hoffman gave me advice to disable this section in the user interface, and after I disabled it, then there were no problems.

So, I came to the conclusion that I was faced with the consequences of bad practice and was punished. Avoid harmful practices. And the ObservableCollection<T> not to blame! Sorry, ObservableCollection<T> .

Now I will learn about TreeView by Josh Smith .

0
source

Source: https://habr.com/ru/post/1245889/


All Articles