How to cast a System.Windows.Controls.SelectedItemCollection?

Matt Searles picture Matt Searles · Dec 10, 2009 · Viewed 25.6k times · Source

I have a method:

private void DeletePuzzle(object param) 
{
}

param is a System.Windows.Controls.SelectedItemCollection, that I got from a WPF ListView's SelectedItems property.

Somehow, I can't seem to cast it from an object to anything useful. I can't create a System.Windows.Controls.SelectedItemCollection because of its protection level, and param won't cast to IList, ICollection or IEnumerable.

How can I iterate through param's items?

Answer

Matt Searles picture Matt Searles · Dec 10, 2009

Right, got it sorted. I kept trying to cast it like

IList<PuzzleViewModel> collection = (IList<PuzzleViewModel>)param;

Which told me it couldn't convert from SelectedItemCollection to IList...

This is in fact what you need to do.

System.Collections.IList items = (System.Collections.IList)param;
var collection = items.Cast<PuzzleViewModel>();