简体   繁体   中英

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.

The XAML is:

<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#:

        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. 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. How do I initialize the DataGrid ItemsSource using VB?

DataGrid.ItemsSource uses/accept collections for displaying data.
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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