Unable to cast object of type ObservableCollection

I break out some Silverlight coding from time to time, to keep the rust off. And most of the time it goes OK – you get the occasional error that come out of nowhere. Like this dreaded one:

Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection' exception

Where did that come from? I had bound a collection of MyGroup items to a ListBox. I later wanted to retrieve the items that were selected by using the SelectedItems collection:

ObservableCollection<MMLService.MyGroup> MyItem = 
(ObservableCollection<MMLService.MyGroup>)SecurityGroupGroups.SelectedItems;

When I tried to cast the ListBox.SelectedItem collections to the type of object I had bound to it, I received this error:

Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[System.Object]' to type 
'System.Collections.ObjectModel.ObservableCollection`1[MML2010.MMService.MyGroup]

My attempts to cast the collection failed. But, I managed to skirt the error by using an Enumerator:

List<Int64> Groups = new List<Int64>();
IEnumerator<object> MyEnum = (IEnumerator<object>)SecurityGroupGroups.SelectedItems.GetEnumerator();
while (MyEnum.MoveNext())
{
    MMLService.MyGroup Temp = (MMLService.MyGroup)MyEnum.Current;
        Groups.Add(Temp.ID);
}

That can’t possibly be the best way to get around that exception. I know this with all my heart. That said, it worked, and I wanted to get around the issue and onto the rest of the code. And for the curious, the error occurred in Silverlight 4.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: