Category / Section
How to create a custom GridColumn ?
2 mins read
SfDataGrid allows you to create custom GridColumn by following the below steps.
- Create a new class by inheriting from the GridColumn. You must specify the GridColumn.CellType property to create a custom column.
- A corresponding CellRenderer class for the custom column must be created by customizing the GridVirtualizingCellRenderer<D, E>.
- You should override the below methods in the created cell renderer class.
- OnCreateDisplayUIView() – to create the cell content to be loaded inside the grid cell.
- OnInitializeDisplayView() – to initialize the cell content loaded inside the grid cell with required settings.
- Finally, you must add the custom column to the SfDataGrid.Columns collection and its renderer in the SfDataGrid.CellRenderers collection.
Note:
D- type of the view that should be placed inside cells in display mode
E- type of the view that should be placed inside cells in edit mode
For example, refer the below example in which a custom column is created for loading a Stepper control in the grid columns. Since the Stepper control is loaded the LoadUIView property is set as true. A custom renderer class is written to load Stepper control as both display and edit views.
Creating Stepper Column
public class StepperColumn: GridColumn { public StepperColumn() { this.LoadUIView = true; var cellType = typeof(GridColumn).GetRuntimeProperties().FirstOrDefault((property) => property.Name == "CellType"); cellType.SetValue(this, "Stepper"); } }
Custom cell renderer for StepperColumn
public class StepperColumnRenderer: GridVirtualizingCellRenderer<Stepper, Stepper> { public StepperColumnRenderer() { IsEditable = true; IsFocusable = true; } public override void OnInitializeDisplayView(DataColumnBase dataColumn, Stepper view) { } protected override Stepper OnCreateDisplayUIView() { return new Stepper(); } }
MainPage
public partial class MainPage : ContentPage { SfDataGrid dataGrid; ViewModel viewModel; public MainPage() { InitializeComponent(); dataGrid = new SfDataGrid() { ColumnSizer = ColumnSizer.Star}; viewModel = new ViewModel(); dataGrid.ItemsSource = viewModel.OrdersInfo; dataGrid.AutoGenerateColumns = false; dataGrid.CellRenderers.Add("Stepper", new StepperColumnRenderer()); var customColumn = new StepperColumn(); customColumn.MappingName = "OrderID"; dataGrid.Columns.Add(customColumn); this.Content = dataGrid; } }
Screenshot
SampleLink: How to create a custom GridColumn?