简体   繁体   中英

cast object to List<T>

I have a MVVM Project one view has a grid that allow multiselect,

<DataGrid x:Name="DataGridBodegas" ItemsSource="{Binding MyLis}" Grid.Row="1">
     <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <cmd:EventToCommand Command="{Binding _MyCommand}" CommandParameter="{Binding ElementName=DataGridBodegas,Path=SelectedItems}"/>
                </i:EventTrigger>
      </i:Interaction.Triggers>
      <DataGrid.Columns>
          <DataGridTextColumn Header="{x:Static resources:Labels.ACOPIO_SeleccioneBodegas}" Width="Auto" Binding="{Binding StrNombreBodega}" ClipboardContentBinding="{x:Null}"/>
      </DataGrid.Columns>
</DataGrid>

At VM I have a ICommand

public override void CommandSelectionChange(object p)
{            
    MyList.RemoveAll(x=> x.IntIdBodega != -1);
    MyList = p as List<Merlin_INV_Bodegas>; // Allways return Null 
}

If I take a look into p object It is a SelectedItemCollection that has elements of my target type, but if try to cast as this

(List<TargetType>)p // Throw exception 
p as List<TargetType> // Allways return null 

foreach( TargetType t in p)
{
} // Throw exception 

My questions are How can I cast p properly to my List?

You can use Linq ToList() :

List<TargetType> list = ((TargetType[])p).ToList();

Or else use the List<> constructor:

List<TargetType> list = new List<TargetType>((TargetType[])p);

If it is a SelectedItemCollection , you need to cast it as an IList first:

List<TargetType> list = ((System.Collections.IList)p).Cast<TargetType>().ToList();

This is because DataGrid.SelectedItems is of type IList not generic IList<T> . So you will have to typecast in IList

var collection = p as IList  

foreach( var item in collection)
{
    var myitem = (TargetType)item;
} 

Since all you're doing is a foreach over the list, I'd suggest you cast to IEnumerable (or IEnumerable<TargetType> ) instead. Using the simplest possible type/interface that you can is a good way of making your code more reusable and understandable.

If you're having trouble casting because the type being passed isn't what you think it is (which seems likely given the comments here so far), I'd suggest you put a breakpoint on the first line of your method, and inspect the value of p in the debugger. That way you can be sure of what's actually being passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM