[英]cast object to List<T>
I have a MVVM Project one view has a grid that allow multiselect, 我有一个MVVM项目,一个视图的网格允许多选,
<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 在VM上,我有一个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 如果我看一下p object
它是一个SelectedItemCollection
,它具有我的目标类型的元素,但是如果尝试这样转换
(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? 我的问题是如何将p正确地投射到列表中?
You can use Linq ToList()
: 您可以使用Linq ToList()
:
List<TargetType> list = ((TargetType[])p).ToList();
Or else use the List<>
constructor: 否则使用List<>
构造函数:
List<TargetType> list = new List<TargetType>((TargetType[])p);
If it is a SelectedItemCollection
, you need to cast it as an IList first: 如果它是SelectedItemCollection
,则需要首先将其强制转换为IList:
List<TargetType> list = ((System.Collections.IList)p).Cast<TargetType>().ToList();
This is because DataGrid.SelectedItems is of type IList
not generic IList<T>
. 这是因为DataGrid.SelectedItems is of type IList
而不是通用IList<T>
。 So you will have to typecast in IList 因此,您将不得不在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. 由于您要做的只是foreach
整个列表,因此建议您将其转换为IEnumerable
(或IEnumerable<TargetType>
)。 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. 如果由于传递的类型不是您认为的那样而在转换时遇到麻烦(到目前为止,此处似乎已给出了注释),建议您在方法的第一行上放置一个断点,并检查调试器中p
的值。 That way you can be sure of what's actually being passed. 这样,您可以确定实际传递的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.