【问题标题】:How do I initialize a WPF datagrid ItemsSource in VB code behind?如何在后面的 VB 代码中初始化 WPF 数据网格 ItemsSource?
【发布时间】: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


【解决方案1】:

DataGrid.ItemsSource 使用/接受集合来显示数据。
看来您正在尝试使用Collection Initializers

正如您自己已经注意到的(来自 cmets),您可以使用数组初始化器

datagrid.ItemsSource = 
{
    New Record With { .FirstName="first1", .LastName="last1" },
    New Record With { .FirstName="first2", .LastName="last2" }
}

或者你可以使用From关键字创建一个列表

datagrid.ItemsSource = New List(Of Record) From
{
    New Record With { .FirstName="first1", .LastName="last1" },
    New Record With { .FirstName="first2", .LastName="last2" }
}

【讨论】:

  • 这是一个非常重要的区别,也是澄清我的问题重点的好点,这实际上是应用集合初始化程序的问题。我还将补充您上面列出的第一种和第二种方法之间有一个有趣的区别。第一种方法似乎不允许在 DataGrid 控件中添加行,但第二种方法会在 DataGrid 底部产生一个空白行,允许在其他 DataGrid 属性设置正确的情况下添加到基础数据。
  • 第一种方法将创建具有两个元素的固定大小的数组。其中 2 方法将创建 List(Of T) 的实例,这将允许向其添加新元素。
猜你喜欢
  • 2010-11-17
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多