简体   繁体   English

如何在VB代码后面初始化WPF datagrid ItemsSource?

[英]How do I initialize a WPF datagrid ItemsSource in VB code behind?

I am trying to learn additional options when using the WPF DataGrid element using Auto-Generated Columns. 我正在尝试使用通过自动生成的列使用WPF DataGrid元素时学习其他选项。

The XAML is: 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"/>

I have this example to initialize the DataGrid ItemsSource in C#: 我有以下示例在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

I wanted to see this in VB, but I'm having difficulty understanding exactly what the C# code above is doing. 我想在VB中看到它,但是我很难准确地理解上面的C#代码在做什么。 Is there some type of casting taking place? 是否正在进行某种类型的转换? My attempts to initialize the DataGrid ItemsSource didn't work because I couldn't figure out how to initialize the DataGrid ItemsSource as an IEnumberable. 我尝试初始化DataGrid ItemsSource的尝试无效,因为我不知道如何将DataGrid ItemsSource初始化为IEnumberable。 How do I initialize the DataGrid ItemsSource using VB? 如何使用VB初始化DataGrid ItemsSource?

DataGrid.ItemsSource uses/accept collections for displaying data. DataGrid.ItemsSource使用/接受集合来显示数据。
Seems you trying use Collection Initializers 似乎您尝试使用集合初始化器

As you already noticed by yourself (from the comments), you can use array initializer 正如您自己已经注意到的(从注释中看到的),可以使用数组初始化器

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

Or you can create a list by using From keyword 或者您可以使用From关键字创建列表

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM