Category / Section
How to bind a column collection from view model in WPF DataGrid (SfDataGrid)?
1 min read
You can bind the SfDataGrid.Columns to a property in the ViewModel by having the binding property to be of type Syncfusion.SfGrid.UI.Xaml.Grid.Columns. So, you can set binding to the SfDataGrid.Columns property provided the DataContext of the WPF DataGrid (SfDataGrid) is ViewModel.
Refer the below code example in which the SfGridColumns property is bind to the SfDataGrid.Columns property.
<Syncfusion:SfDataGrid x:Name="datagrid" AllowEditing="True" AllowFiltering="True" AllowSorting="True" Columns="{Binding SfGridColumns, Mode=TwoWay}" AutoGenerateColumns="False" ItemsSource="{Binding ItemsCollection}" ShowGroupDropArea="True" ShowRowHeader="True"> </Syncfusion:SfDataGrid>
Refer the below code example in which the SfGridColumns columns in the ViewModel is populated with some GridTextColumn when creating the ViewModel instance.
Note that the SfGridColumns property in the ViewModel is of type Syncfusion.SfGrid.UI.Xaml.Grid.Columns.
C#
public class ViewModel { private EmployeeDetails employeeDetails = new EmployeeDetails(); private ObservableCollection<BusinessObjects> itemsCollection; private Columns sfGridColumns; public ViewModel() { SetSfGridColumns(); this.ItemsCollection = employeeDetails; } public ObservableCollection<BusinessObjects> ItemsCollection { get { return itemsCollection; } set { itemsCollection = value; } } public Columns SfGridColumns { get { return sfGridColumns; } set { this.sfGridColumns = value; } } protected void SetSfGridColumns() { this.sfGridColumns = new Columns(); sfGridColumns.Add(new GridTextColumn() { MappingName = "EmployeeName" }); sfGridColumns.Add(new GridTextColumn() { MappingName = "EmployeeAge" }); sfGridColumns.Add(new GridTextColumn() { MappingName = "EmployeeSalary" }); sfGridColumns.Add(new GridTextColumn() { MappingName = "ExperienceInMonth" }); } }