XamDataGrid tips and tricks

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

The following is a general list of tips and tricks for working with the XamDataGrid. Primarily code/xaml which doesn’t require a full post of their own.

Enable/disable column sorting or change the way the sorting is applied

Simply set the LabelClickAction on the FieldSettings to “Nothing” to turn sorting off. You can also change the logic for sort in that you can set the sorting to single or multi field.

<igDP:XamDataGrid>
   <igDP:XamDataGrid.FieldSettings>
      <igDP:FieldSettings LabelClickAction="Nothing" />
   </igDP:XamDataGrid.FieldSettings>
</igDP:XamDataGrid>

Changing cell styles and more in code-behind

Sometimes our requirement is too dynamic for the declarative nature of XAML and/or may be difficult to handle via styles/triggers and converters so we need to write some code. The problem is getting at the cell object at the right time.

This is where the CellsInViewChanged event is useful, for example

private void CellsInViewChanged(object sender, CellsInViewChangedEventArgs e)
{
   foreach(var visibleDataBlock in e.CurrentCellsInView)
   {
      foreach(var record in visibleDataBlock.Records)
      {
         foreach(var field in visibleDataBlock.Fields)
         {
            var cellValuePresenter = CellValuePresenter.FromRecordAndField(record, field);
            // do something with the cell value presenter
         }
      }
   }
}

In the above code (which we seem to have to attach an event handler to, i.e. there’s no virtual method for deriving our own implementation from that I can see). We get a list of VisibleDataBlock items which we loop through to get the records and the fields. Using the CellValuePresenter.FromRecordAndField we can then get the CellValuePresenter where we can then change visual style directly, such as the cell background colour, we can make the cell’s editor readonly and so on.

How to stop a cell “appearing” to go into edit mode

We may set a cell’s editor to readonly but when the user clicks on the cell the cell changes colour as if switching to edit more and the caret is displayed, even though you cannot edit the field. A way to stop this happening is by overriding the OnEditModeStarting method in a subclassed grid control or intercepting the EditModeStarting event on the grid. For example

protected override void OnEditModeStarting(EditModeStartingEventArgs args)
{
   // required to stop the cell even entering edit mode
   var cvp = CellValuePresenter.FromCell(args.Cell);
   if (cvp != null)
   {
      args.Handled = args.Cancel = cvp.Editor.IsReadOnly;
   }
}