簡體   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