Cell Alignment in DataGrid in WPF


Introduction

In this article we will see how we can change the Cell Alignment in DataGrid in WPF.

Creating WPF Application Project

Fire up Visual Studio 2008 and Create a WPF Application and name the project as CellAlignmentDataGridWPF.

CellAlignmentInDataGridFig1.gif

Let's have a DataGrid and then we would bind some sample data to it, so that we can visualize the Data in DataGrid.

CellAlignmentInDataGridFig2.gif

The above class represents the structure of Employee Entity.

Now we would have some sample data and bind it to DataGrid.

CellAlignmentInDataGridFig3.gif

Now we will run the application and see how the cell alignment are look by default.

CellAlignmentInDataGridFig4.gif

As you see in above display the default alignement of the DataGrid Cell is Left Alignment.

Now we would try to have Right and Center Alignement for Cells too.

We have to create a style that would Change the Template of DataGridCell, so let's do it.

CellAlignmentInDataGridFig5.gif

The above styles are for DataGridCell. Now we will use Custom columns in our DataGrid and have these styles applied on.

CellAlignmentInDataGridFig6.gif

Now let's see how does it look in run time.

CellAlignmentInDataGridFig7.gif

As simple as that. So we have achieved the Cell Alignment in DataGrid.

Hope this article helps.