I'm dynamically populating a silverlight listbox, programmatically, with a template control.
the listbox is empty, and when i attempt a listBox.Items.Add(myTemplateControl), it throws the "Value does not fall within the expected range" argumentexception.
i verified in the debugger that the item collection is indeed emtpy.
the only time i've heard of this exception happening is when the list already contains an instance with that name.
any thoughts?
Stack trace:
at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at MS.Internal.XcpImports.MethodPack(IntPtr objectPtr, String methodName, Object[] rawData)
at MS.Internal.XcpImports.Collection_Add[T](PresentationFrameworkCollection`1 collection, Object value)
at System.Windows.PresentationFrameworkCollection`1.AddImpl(Object value)
at System.Windows.Controls.ItemCollection.AddImpl(Object value)
at System.Windows.Controls.ItemCollection.AddInternal(Object value)
at System.Windows.PresentationFrameworkCollection`1.Add(T value)
at KTClientRIA.Documents.b__4(Object sender, DownloadStringCompletedEventArgs e)
at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
Thanks to all the suggestions. I was able to track it down. At another point in time of the life cycle of the silverlight control, there was another listbox completely separate from this one that was adding an item of the same name.
being that both the parent listboxes resided on the same silverlight control, it was blowing up.
I apologize in advance for this being a "non-answer" answer, but maybe it will help.
I had the exact same issue, but with an Accordion instead of a ListBox. My control hierarchy was:
- UserControl (the page)
- Accordion
- AccordionItem0
- ContentControl
- ReportView0 (dynamically created at runtime and bound to the ContentControl's Content property)
- AccordionItem1
- ContentControl
- ReportView1 (dynamically created at runtime and bound to the ContentControl's Content property)
- etc.
I was able to populate the accordion's ItemSource and create the ReportView controls the first time, but if I tried to refresh the list (say, to sort it), I would get the "Value does not fall within the expected range" exception.
I believe what was happening was that, when I freshed the list, my manually created ReportView items were never being disassociated from their original parent ContentControls. After the refresh, when attempting to bind the ReportViews to a different AccordionItem, the exception was being thrown because each ReportView was already in the visual tree.
My solution was to get rid of the ContentControl and declare the ReportView control in its place. This way, Silverlight would manage the control in the visual tree.
(I originally used the dynamic approach so that I could use MEF to satisfy imports via GetExportedValue. When I found out about CompositionInitializer.SatisfyImports, I was able to switch to declaring the ReportView in XAML.)