Search code examples
c#wpfuser-controls

DataGrid in User Control throws exception Unable to cast object of type 'MS.Internal.NamedObject'


I have a project containing a DataGrid which I've implemented a handy sorting and filtering UI for. It's so handy in fact that I've extracted the relevant code into a UserControl which I've embedded in a test project. I've added DependencyProperties for the DataGrid controls which I want available to the consumer of the UserControl. So far so good.

The problem began when I set the DataGrid property IsReadOnly="False". At that point any operation on its ItemsSource throws an exception.

The DataGrid in the original project is perfectly happy with IsReadOnly="False" and the UserControl works OK with IsReadOnly="True". In the debugger (VS 2017) everything is correctly typed and all the data is as expected.

One failure occurs at the code below

this.Xrefs.Cast<ProductXref>().ToList()

where

public ICollectionView Xrefs { get; set; }

is set from my ItemsSource DependencyProperty.

In other locations I get an Object does not match target type exception. Is VS wrapping the ItemsSource collection in another object but only when the DataGrid is in a UserControl and is set to not readonly?

I appreciate that I can leave the DataGrid readonly and use a child form for editing a row, but I prefer editing in place if possible.


Solution

  • Instead of casting all items in the collection view, you could use the OfType<T> method to only get the ProductXref objects:

    this.Xrefs.OfType<ProductXref>().ToList();
    

    There may be other type of objects in the collection view, like for example a placeholder for the last "empty" row that you will typically see in a DataGrid.