WPF ItemSource 返回 null
我有一个命名类,
public class testClass
{
public testClass(string showCode, string urn)
{
ShowCode = showCode;
URN = urn;
}
public string ShowCode { get; set; }
public string URN { get; set; }
}
我创建一个 ArrayList,添加到列表并将其绑定到 wpf 数据网格,
ArrayList l = new ArrayList();
l.Add(new testClass("ose11", "7016463"));
this.grdTestData.ItemsSource = l;
这显示了我想要在数据网格中显示的内容。
现在我想取回数据网格的数据并迭代它
IEnumerable<testClass> t = this.grdTestData.ItemsSource as IEnumerable<testClass>;
..但是“t”为空! !!这就是问题所在!
这是数据网格的定义:
<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="12,66,0,48" Name="grdTestData" Width="200" CanUserAddRows="True" >
<DataGrid.Columns>
<DataGridTextColumn Header="ShowCode" Binding="{Binding ShowCode}" />
<DataGridTextColumn Header="URN" Binding="{Binding Path=URN}" />
</DataGrid.Columns>
</DataGrid>
I have a named class
public class testClass
{
public testClass(string showCode, string urn)
{
ShowCode = showCode;
URN = urn;
}
public string ShowCode { get; set; }
public string URN { get; set; }
}
I create an ArrayList, add to the list and bind it to a wpf datagrid
ArrayList l = new ArrayList();
l.Add(new testClass("ose11", "7016463"));
this.grdTestData.ItemsSource = l;
This displays just what I want in the datagrid.
Now I want to get the datagrid's data back and iterate throught it
IEnumerable<testClass> t = this.grdTestData.ItemsSource as IEnumerable<testClass>;
..but 't' is null! !! this is the problem !!
This is the datagrid definition:
<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="12,66,0,48" Name="grdTestData" Width="200" CanUserAddRows="True" >
<DataGrid.Columns>
<DataGridTextColumn Header="ShowCode" Binding="{Binding ShowCode}" />
<DataGridTextColumn Header="URN" Binding="{Binding Path=URN}" />
</DataGrid.Columns>
</DataGrid>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ItemsSource 不为 null,只是
ArrayList
未实现IEnumerable
,因此您执行的转换会返回null
。如果您使用,您将收到一条错误消息,指出此转换无效。
如果您使用
List
而不是ArrayList
作为源,则转换将有效并且不会返回 null。如果您不想使用泛型集合,则可以将其转换为 ArrayList 或 IEnumerable(非泛型)(如果您希望拥有接口)。
The ItemsSource is not null, it's just that
ArrayList
does not implementIEnumerable<testClass>
, and therefore the cast you perform returnsnull
. If you useyou will get an error saying that this cast is not valid.
If you use a
List<testClass>
instead ofArrayList
for the source, the cast will be valid and not return null.If you don't wish to use a generic collection, then cast it to
ArrayList
orIEnumerable (non-generic)
instead, if you wish to have an interface.