【问题标题】:WPF ItemSource returns nullWPF ItemSsource 返回 null
【发布时间】:2011-10-02 15:39:02
【问题描述】:

我有一个命名类

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>

【问题讨论】:

  • 请使用正确的代码格式,您的帖子很难阅读。

标签: wpf datagrid ienumerable itemsource


【解决方案1】:

ItemsSource 不为空,只是ArrayList 没有实现IEnumerable&lt;testClass&gt;,因此您执行的转换返回null。如果你使用

var list = (IEnumerable<testClass>) datagrid.ItemsSource;

您将收到一条错误消息,指出此转换无效。

如果您使用 List&lt;testClass&gt; 而不是 ArrayList 作为源,则转换将有效且不返回 null。

如果您不想使用通用集合,请将其转换为 ArrayListIEnumerable (non-generic),如果您希望有一个接口。

【讨论】:

  • 感谢您的解释,这使我能够说得对。解决了。​​
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2021-02-14
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
相关资源
最近更新 更多