I am creating a control (CustomGrid) that inherits from the WPF DataGrid. Whenever the CustomGrid is used, it will have the ItemsSource set to an Observable Collection. One of the features I am adding is the ability to paste data from the clipboard, however if there are not enough rows currently in the collection, then I want to add additional rows. This is where I am stuck. The CustomGrid will be used for different collections, and therefore I cannot reference the class that the collection is based on. Using the ItemsSource, how can I add an additional row.
This is what I have tried so far...
private void AddNewRow()
{
IList itemsSource = this.ItemsSource as IList;
Type itemType = itemsSource.GetType().GenericTypeArguments[0];
object newRecord = Activator.CreateInstance(itemType);
itemsSource.Add(newRecord);
}
Error: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
Any idea what I might be doing wrong?
I have been thinking about this consistently for the last 24 hours and have come to the conclusion that it cannot be done. The only way this will work is if there is already data in the collection, but if somebody is pasting data into the DataGrid and the collection is empty, then it is impossible to get that object that the collection is based on.