Unbound Column in WPF DataGrid (SfDataGrid)

28 May 202415 minutes to read

SfDataGrid allows you to add additional columns which are not bound with data object from underlying data source. You can add unbound column using GridUnBoundColumn class. Unbound columns supports for sorting, filtering, grouping, exporting and printing as normal columns.

<syncfusion:SfDataGrid x:Name="dataGrid"                                                                       
                       AutoGenerateColumns="False" 
                       ItemsSource="{Binding Orders}">
    <syncfusion:SfDataGrid.Columns>
        <syncfusion:GridUnBoundColumn   Expression="UnitPrice*Discount"
                                                                        HeaderText="Discount Price"
                                                                        MappingName="DiscountPrice" />
    </syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
this.dataGrid.Columns.Add(new GridUnBoundColumn() { HeaderText = "Discount Price", MappingName = "DiscountPrice", Expression = "UnitPrice*Discount" });

Unbound Column in WPF DataGrid

NOTE

It is mandatory to specify the GridColumn.MappingName for GridUnBoundColumn with some name to identify the column. It is not necessary to define name of field in the data object.

Populating data for unbound column

You can populate the data for unbound column by setting Expression or Format property or through QueryUnBoundColumnValue event.

Using Expression

You can specify the arithmetic or logic expression using Expression property to compute the display value. By default GridUnBoundColumn evaluates the expression with casing. You can disable the casing while evaluate the expression by setting CaseSensitive property to false.

Below are the list of Arithmetic and logical operations supported.

Arithmetic operations Operator
Add +
Subtract -
Multiply *
Divide /
Power ^
Mod %
Greater Than >
Less Than <
Equal =
GreaterThanOrEqual >=
LessThanOrEqual <=
Logical operations Operators
AND (char)135
OR (char)136
NOT (char)137
<syncfusion:SfDataGrid x:Name="dataGrid"                                                                       
                       AutoGenerateColumns="False" 
                       ItemsSource="{Binding Orders}">
    <syncfusion:SfDataGrid.Columns>
        <syncfusion:GridUnBoundColumn HeaderText="Unbound Column"
                                      MappingName="UnboundColumn" />
    </syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
(this.dataGrid.Columns[3] as GridUnBoundColumn).Expression = "Discount * UnitPrice > 0" + (char)135 + "UnitPrice * Quantity > 100";

WPF DataGrid displays Unbound Column with Expression

Using Format

You can format the values of other columns and display the formatted value in unbound column using Format property.

<syncfusion:SfDataGrid x:Name="dataGrid"
                       AutoGenerateColumns="False" 
                       ItemsSource="{Binding Orders}">
    <syncfusion:SfDataGrid.Columns>
        <syncfusion:GridUnBoundColumn Format="'{Discount}% for {OrderID}'"
                                      HeaderText="Discount Price"
                                      MappingName="DiscountPrice"/>
    </syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
this.dataGrid.Columns.Add(new GridUnBoundColumn() { HeaderText = "Discount Price", MappingName = "DiscountPrice", Format = "'{Discount}% for {OrderID}'" });

Formatting Unbound Columns in WPF DataGrid

Using QueryUnBoundColumnValue event

You can populate the data for unbound column by handling the QueryUnBoundColumnValue event.
GridUnBoundColumnEventArgs of the QueryUnBoundColumnValue event provides the information about the cell triggered this event. GridUnBoundColumnValueEventsArgs.OriginalSender returns the DataGrid fired this event for DetailsView.

You can get or set the GridUnBoundColumnEventArgs.Value property based on the UnBoundAction.

  • UnBoundAction - QueryData denotes the event triggered to query value and cell information.
  • UnBoundAction - CommitData denotes the event triggered to save the edited value.
this.dataGrid.QueryUnboundColumnValue += dataGrid_QueryUnboundColumnValue;

void dataGrid_QueryUnboundColumnValue(object sender, GridUnboundColumnEventsArgs e)
{

    if (e.UnBoundAction == UnBoundActions.QueryData)
    {
        var unitPrice = Convert.ToDouble(e.Record.GetType().GetProperty("UnitPrice").GetValue(e.Record));
        var disCount = Convert.ToDouble(e.Record.GetType().GetProperty("Discount").GetValue(e.Record));
        var save = unitPrice * disCount;
        e.Value = save.ToString() + "$";
    }
}

Populating data with Unbound Column in WPF SfDataGrid

Refreshing the unbound column at runtime

You can trigger the QueryUnBoundColumnValue event or recalculate the value for the cells of unbound column at runtime by calling UpdateUnboundColumn method.

this.dataGrid.CurrentCellEndEdit +=dataGrid_CurrentCellEndEdit;

void dataGrid_CurrentCellEndEdit(object sender, CurrentCellEndEditEventArgs args)
{
    this.dataGrid.UpdateUnboundColumn(this.dataGrid.CurrentItem, "Discount");           
}

Editing unbound column

Cancel the editing for unbound column cell

You can cancel the editing of unbound column cell by handling the SfDataGrid.CurrentCellBeginEdit event.

dataGrid.CurrentCellBeginEdit += dataGrid_CurrentCellBeginEdit;

void dataGrid_CurrentCellBeginEdit(object sender, CurrentCellBeginEditEventArgs args)
{                                                 
    args.Cancel = args.Column is GridUnBoundColumn;    
}

Saving edited value of unbound column using QueryUnBoundColumnValue.

You can get the edited value of unbound column from GridUnboundColumnEventsArgs.Value property of QueryUnBoundColumnValue event when UnBoundAction is CommitData.

this.dataGrid.QueryUnboundColumnValue += dataGrid_QueryUnboundColumnValue;

void dataGrid_QueryUnboundColumnValue(object sender, GridUnboundColumnEventsArgs e)
{

    if(e.UnBoundAction == UnBoundActions.CommitData)
    {
        var editedValue = e.Value;
    }
}

Read unbound column values

You can get the value of GridUnBoundColumn using GetUnBoundCellValue method.

using Syncfusion.UI.Xaml.Grid.Helpers;
this.dataGrid.CurrentCellValueChanged += dataGrid_CurrentCellValueChanged;

void dataGrid_CurrentCellValueChanged(object sender, CurrentCellValueChangedEventArgs args)
{
    var updateValue = this.dataGrid.GetUnBoundCellValue(dataGrid.Columns[5], this.dataGrid.CurrentItem); 
}

Styling unbound column

You can customize the style of unbound column by writing style of TargetType GridCell or setting GridColumn.CellStyle property.

In the below code snippet, Foreground of the cells in GridUnBoundColumn changed based on its content.

<Window.Resources>
        <local:UnboundCellStyleConverter x:Key="unboundCellStyleConverter"/>
</Window.Resources>

<syncfusion:SfDataGrid x:Name="dataGrid"                                                                       
                       AutoGenerateColumns="False" 
                       ItemsSource="{Binding Orders}">
            <syncfusion:SfDataGrid.Columns>
                <syncfusion:GridUnBoundColumn HeaderText="Discount Price"
                                              MappingName="DiscountPrice">
                    <syncfusion:GridUnBoundColumn.CellStyle>
                        <Style TargetType="syncfusion:GridCell">
                           <Setter  Property="Foreground"  Value="{Binding   RelativeSource={RelativeSource Self}, Converter={StaticResource unboundCellStyleConverter}}" />
                        </Style>
                    </syncfusion:GridUnBoundColumn.CellStyle>
                </syncfusion:GridUnBoundColumn>            
    </syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
public class UnboundCellStyleConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var unboundCell = value as GridCell;
        var unboundValue = (unboundCell.Content as TextBlock).Text;
        var data = System.Convert.ToInt16(unboundValue.Substring(0,unboundValue.Length -1));

        if(data > 30)
            return new SolidColorBrush(Colors.DarkGreen);
        return new SolidColorBrush(Colors.Red);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}

Customizing Unbound Column Style in WPF DataGrid

You can refer the Styling section of GridColumn for more information.

Customize the Unbound column behavior

SfDataGrid allows you to customize the operations like key navigation and UI related interactions by overriding the corresponding renderer associated with the unbound column.
Below table lists the available cell types for unbound column.

Cell Type Renderer
UnBoundTemplateColumn

GridUnBoundCellTemplateRenderer

UnBoundTextColumn

GridUnBoundCellTextBoxRenderer

If the GridUnBoundColumn.EditTemplate not defined then the UnboundTextColumn set as default cell type of GridUnBoundColumn.
If GridUnBoundColumn.EditTemplate property defined then UnBoundTemplateColumn set as cell type of GridUnBoundColumn.

Overriding Existing CellType

You can customize the unbound row cell behavior by overriding existing renderer and replace the default one in SfDataGrid.CellRenderers.

In the below code snippet, GridUnBoundCellTextBoxRenderer is customized to change the foreground and replaced the default renderer with customized renderer in SfDataGrid.CellRenderer collection.

this.dataGrid.CellRenderers.Remove("UnBoundTextColumn");
this.dataGrid.CellRenderers.Add("UnBoundTextColumn", new GridUnBoundCellTextBoxRendererExt());

public class GridUnBoundCellTextBoxRendererExt : GridUnBoundCellTextBoxRenderer
{

    public override void OnInitializeDisplayElement(DataColumnBase dataColumn, TextBlock uiElement, object dataContext)
    {
        object cellValue = null;

        if (dataContext != null)
            cellValue = DataGrid.GetUnBoundCellValue(dataColumn.GridColumn, dataContext);
        uiElement.Text = cellValue == null ? string.Empty : cellValue.ToString(); ;
        uiElement.Foreground = new SolidColorBrush(Colors.Blue);
    }

    public override void OnInitializeEditElement(DataColumnBase dataColumn, TextBox uiElement, object dataContext)
    {                
        object cellValue = null;

        if (dataContext != null)
            cellValue = DataGrid.GetUnBoundCellValue(dataColumn.GridColumn, dataContext);
        uiElement.Text = cellValue == null ? string.Empty : cellValue.ToString();        
    }
}

Customizing Unbound Column behavior in WPF SfDataGrid

Custom Renderer

You can change the renderer of unbound column by removing the predefined cell type value from CellRenderers collection and add the newly derived renderer from GridVirtualizingCellRenderer. Refer the Create the renderer for existing column section for more information to create the custom renderer in columns section.

Templating unbound column

You can load any WPF control in the display mode for GridUnBoundColumn by setting GridColumn.CellTemplate property. In edit mode, corresponding editor will be loaded based on column type. You can refer the CellTemplate section of GridColumn and GridTemplateColumn for more information.