77

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?

Alex Deen
  • 25
  • 3
Matt Searles
  • 2,656
  • 2
  • 16
  • 18
  • 1
    What error do you get when you try to cast `param` to `IEnumerable`? Also, have you tried casting it to `IEnumerable`? `SelectedItemCollection` inherits from `ObservableCollection` which means you should have no problem casting it to `IEnumerable`, `IEnumerable`, `ICollection`, `ICollection`, or `IList`, `IList`. – Adam Maras Dec 10 '09 at 00:50

3 Answers3

142

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>();
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
Matt Searles
  • 2,656
  • 2
  • 16
  • 18
  • 2
    You can also under certain situations, convert directly to what you need. If you want a `List` or an `Array` you can just do `var collection = items.Cast().ToArray()` or `var collection = items.Cast().ToList()` – David Bentley Dec 02 '17 at 18:30
1

from reflector : -

[Category("Appearance"), Bindable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IList SelectedItems
{
    get
    {
        return base.SelectedItemsImpl;
    }
}

Selected Items of ListView is an IList, id like to see the calling method.

Aran Mulholland
  • 23,555
  • 29
  • 141
  • 228
  • 1
    The calling method was from a RelayCommand (Josh Smiths version). The SelectedItemCollection was getting through ok, but one has to cast it to an IList, not an IList, and then cast that. – Matt Searles Dec 10 '09 at 03:30
-6

Check The Type: System.Collections.Generic.IList<(Of <(ListViewDataItem>)>)

Alex Deen
  • 25
  • 3
pipelinecache
  • 3,954
  • 1
  • 17
  • 16