How to set the alignment of WPF DataGrid cell in code

Nov 18, 2009 at 8:31 AM
Edited Nov 18, 2009 at 8:32 AM

I wish to set the alignment of a column of WPF DataGrid to be right, and I wrote the code as follows,

ColumnIndex = 2;
// Set the alignment of the double column
if (grid.Columns.Count > ColumnIndex)
{
    grid.Columns[ColumnIndex].CellStyle = new Style(typeof(DataGridCell));
    grid.Columns[ColumnIndex].CellStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Right));
}

but there was an exception like "after using SetterBaseCollection(sealed), you can not change it" when I compiled the project.

So how will I change the code?

Dec 14, 2009 at 8:20 AM

Style alignStyle = new Style(typeof(DataGridCell));
alignStyle.Setters.Add(new Setter(DataGridCell.WidthProperty, 20.0));
alignStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Center));
alignStyle.Setters.Add(new Setter(DataGridCell.VerticalAlignmentProperty, VerticalAlignment.Center));
this.Columns[0].CellStyle = alignStyle; 

thanks, I have solved the issue above.