【发布时间】:2017-08-13 15:48:49
【问题描述】:
在使用 WPF DataGrid 元素和自动生成的列时,我正在尝试学习其他选项。
XAML 是:
<Window x:Class="DataGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DataGrid with Autogenerated Columns" Height="350" Width="525">
<DataGrid Name="dataGrid"/>
我有这个例子在 C# 中初始化 DataGrid ItemsSource:
public MainWindow()
{
InitializeComponent();
dataGrid.ItemsSource = new Record[]
{
new Record { FirstName="first1", LastName="last1"},
new Record { FirstName="first2", LastName="last2" }
};
}
Class Record is defined in another file
我想在 VB 中看到这一点,但我很难理解上面的 C# 代码在做什么。是否有某种类型的铸造发生?我初始化 DataGrid ItemsSource 的尝试没有奏效,因为我不知道如何将 DataGrid ItemsSource 初始化为 IEnumberable。如何使用 VB 初始化 DataGrid ItemsSource?
【问题讨论】:
-
如何将 DataGrid 初始化为 IEnumberable 是什么意思?
DataGrid是UI控件,不能初始化为IEnumerable。 -
在
vb.net你也可以这样做:datagrid.ItemsSource = New Record() From { new Record { .FirstName="first1", .LastName="last1" }} -
我刚刚更新了我的帖子,更清楚地表明这是我正在尝试初始化的 ItemsSource。我试过你的解决方案。不接受 From 关键字说“无法使用集合初始化程序初始化类型 'Record',因为它不是集合类型”。编辑器将接受 With 关键字,但在运行时失败,因为它不会强制转换。
-
这是我尝试使用的行:
dataGrid.ItemsSource = New Record() With {.FirstName = "first1", .LastName = "last1"}。运行时错误是“无法将 'Ch10_ItemsControls.Record' 类型的对象转换为 'System.Collections.IEnumerable'。” -
抱歉,您需要明确定义一个集合:
datagrid.ItemsSource = New List(Of Record) From { new Record With { .FirstName="first1", .LastName="last1" }}
标签: c# wpf vb.net xaml datagrid