Articles in this section
Category / Section

How to bind a column collection from view model in .NET MAUI DataGrid?

2 mins read

The .NET MAUI DataGrid supports binding the SfDataGrid.Columns to a property in the ViewModel by having the binding property to be of type ColumnCollection or List<DataGridColumn> in the ViewModel.

Refer to the code example below in which the DataGridColumns property is bound to the SfDataGrid.Columns property.

XAML
In the XAML page, bind the DataGridColumns property to the SfDataGrid.Columns.

<syncfusion:SfDataGrid  x:Name="datagrid"
                        ItemsSource="{Binding Employees}"
                        Columns="{Binding DataGridColumns}"
                        AutoGenerateColumnsMode="None"
                        DefaultColumnWidth="155">
</syncfusion:SfDataGrid>

ViewModel.cs
Create a property in the ViewModel class to bind with a type that can be either List<DataGridColumn> or Syncfusion.Maui.DataGrid.ColumnCollection. Assign the appropriate values to this property within the constructor.

private ColumnCollection dataGridColumns;

public ColumnCollection DataGridColumns
{
    get { return dataGridColumns; }
    set
    {
        dataGridColumns = value;
    }
}
public EmployeeViewModel()
{
    this.DataGridColumns = new ColumnCollection
    {
        new DataGridNumericColumn(){ MappingName = "EmployeeID" , HeaderText="Employee ID"},
        new DataGridTextColumn(){ MappingName = "Name" , HeaderText = "Name"},
        new DataGridTextColumn(){ MappingName = "IDNumber", HeaderText ="ID Number"},
    };

}

The following screenshot shows column collection bound from a property in a view model.

SfDataGrid_Binding_Columns.png

Download the complete sample from GitHub

Conclusion
I hope you enjoyed learning how to bind a column collection from the view model in .NET MAUI DataGrid.

You can refer to our .NET MAUI DataGrid feature tour page to learn about its other groundbreaking feature representations. Explore our .NET MAUI DataGrid Documentation to understand how to present and manipulate data.
For current customers, check out our .NET MAUI components from the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI DataGrid and other .NET MAUI components.
Please let us know in the comments section if you have any queries or require clarification. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied