How to Align Text in DataGrid Cell in Xaml and in Code Behind

Hello,

While answering a query on silverlight forum, I thought of writing this article.
Quoting the question as:

DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = "Result";
textColumn.Binding = new Binding("Result");
dataGrid1.Columns.Add(textColumn);

how i can set RESULT alignment right?

Here is what you have to do, I will show you this in both ways like doing it in Xaml Page and doing it in code behind.

First add the Style in your User Control Resource:

<UserControl.Resources>
      <Style x:Key="AlignRight" TargetType="Data:DataGridCell">
          <Setter Property="HorizontalContentAlignment" Value="Right" />
     </Style>
</UserControl.Resources>
 
I'm doing this for Right Align but you can change it according to your requirement.
 
Next, how to do this in Xaml Page? Its very simple, apply this style to whichever column you want, like this:
 
<Data:DataGridTextColumn Header="Amount" Width="90" Binding="{Binding Amount}" IsReadOnly="True" CellStyle="{StaticResource AlignRight}"></Data:DataGridTextColumn>
 
Now how to do this in code behind:
 
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = "Result";
textColumn.Binding = new Binding("Result");
textColumn.CellStyle = Resources["AlignRight"] as Style;
dataGrid1.Columns.Add(textColumn);

Comments are always welcome.

Happy Coding :)

4 comments:

  1. Thanks. It was useful to me.

    It might be useful for new comers to have the declaration of "data"

    --Raghav

    ReplyDelete
  2. Very help full by the lines (columns separators) in the grid does not display properly any more

    ReplyDelete