Search code examples
c#datatabledatagridwinui-3

WinUI3 | DataGrid ItemsSource DataTable


I want to make a WinUI3 (Win32) application with a DataGrid from Microsoft.Toolkit. I use MVVM.

My XAML code:

`
        <controls:DataGrid
            Grid.Row="1" Grid.Column="0"
            ItemsSource="{Binding DataTableViewModel}"
            Margin="12"
            VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
            AutoGenerateColumns="True"
            CanUserSortColumns="False"
            CanUserReorderColumns="True"
            CanUserResizeColumns="True"
            ColumnHeaderHeight="32"
            MaxColumnWidth="400"
            HeadersVisibility="Column"
            IsReadOnly="True"
            SelectionMode="Extended">
        </controls:DataGrid>

The problem is that binding DataTable doesn't work. Error message: Error: Converter failed to convert value of type '' to type 'IBindableIterable'; BindingExpression: Path='DataTableViewModel' DataItem='DemoApp.ViewModel.ViewModel'; target element is 'CommunityToolkit.WinUI.UI.Controls.DataGrid' (Name='null'); target property is 'ItemsSource' (type 'IBindableIterable').

I can bind a collection and it does work, but the problem is I need a DataTable to fill the datagrid as I need it (for example headers are the first column and not the first row...).

How is it possible to bind a DataTable to a WinUI3 DataGrid?


Solution

  • How is it possible to bind a DataTable to a WinUI3 DataGrid?

    The Windows Community Toolkit DataGrid is essentially composed of many ListViews, you need to use the DataGrid.ItemsSource property to bind to a collection.

    Here are the official documents for your reference