I had a similar problem because the user was able to define the columns of the grid at runtime.
I wrote a control containing the xam datagrid and exposing a DataSource dependency property to bind the model for the grid (i.e. a data table).
Every time the source changed (you can add event listeners for PropertyChanged and the grids FieldLayoutInitializing event) the grid was dynamically re-rendered by clearing its datasource and resetting it:
private void ReRenderGrid()
{
XamDataGrid.FieldLayouts.Clear();
XamDataGrid.ClearValue(DataPresenterBase.DataSourceProperty);
XamDataGrid.DataSource = DataSource.Data.DefaultView;
}
The columns are re configured by an event handler on the following event which is raised by xamdatagrid after the grids datasource is reset:
XamDataGrid.FieldLayoutInitializing += LayoutInitializing;
Handler:
private void LayoutInitializing(object sender, FieldLayoutInitializingEventArgs e)
{
const string deletebuttonstyle = "DeleteButtonStyle";
const string requiredinputvalue = "RequiredInputValue";
const string optionalinputvalue = "OptionalInputValue";
const string outputvalue = "OutputValue";
var fieldLayout = e.FieldLayout;
fieldLayout.Fields.Clear();
AddFields(DataSource.InColumns, requiredinputvalue, fieldLayout);
AddSplitter(fieldLayout);
AddFields(DataSource.OptionalInColumns, optionalinputvalue, fieldLayout);
AddSplitter(fieldLayout);
AddFields(DataSource.OutColumns, outputvalue, fieldLayout);
AddUnboundField(fieldLayout, string.Empty, GetStyle(deletebuttonstyle));
}
In my case the datasource contained all columns the user configured. AddFields calls this method for each list entry:
private void AddField(string name, Style style, FieldLayout fieldLayout)
{
var field = new Field {Name = name};
field.Settings.LabelPresenterStyle = style;
field.Settings.CellValuePresenterStyle = GetStyle("StandardCellValueStyle");
fieldLayout.Fields.Add(field);
}
AddSplitter and AddUnboundField are implemented in a similar fashion.