How to get a WPF DataGrid cell to right align without making the selectable area on a new row tiny?

Tod picture Tod · Oct 18, 2011 · Viewed 62k times · Source

I'm using a WPF4.0 DataGrid. When double clicking on a cell in a new row everything works fine unless I've added a cell style to that column. For example, I have a numeric column where I want the data right aligned so the xaml looks like this

<DataGridTextColumn Binding="{Binding Path=ImpaId}"
                    CellStyle="{StaticResource CellRightAlign}">
     <DataGridTextColumn.Header>
          <TextBlock  Style="{StaticResource DataGridHeader}">Impa</TextBlock>
     </DataGridTextColumn.Header>
</DataGridTextColumn>

Where the style in a shared resource is just:

<Style x:Key="CellRightAlign">
    <Setter Property="Control.HorizontalAlignment"
            Value="Right" />
</Style>

The resulting selectable area on a new row is shown in the image as that small blue area.This is a very small target for the user to hit, and this happens to be the most likely column they will want to start with on a new row.

DataGrid cell with tiny width

If I remove the CellStyle, the area works as desired but of course I lose the right alignment.

DataGrid cell with proper width

Does anyone know how to achieve both?

Things I tried

  1. Setting TargetNullValue on the binding to a format with some width. This works on existing rows but has no effect on a new row.
  2. Setting MinWidth on the column, this did not affect the width of the new row selectable area.

Thing that worked:

Using the information from the answer by @AngelWPF I was able to change from using CellStyle to using ElementStyle as follows:

<DataGridTextColumn Binding="{Binding Path=ImpaId}"
                    CellStyle="{StaticResource CellRightAlign}">

Became

<DataGridTextColumn Binding="{Binding Path=ImpaId}"
                    ElementStyle="{StaticResource CellRightAlign}">

Answer

WPF-it picture WPF-it · Oct 18, 2011

You could apply ElementStyle on the DataGridTextColumn targetted to TextBlock and right align that, it would work.

      <DataGridTextColumn Binding="{Binding Path=ImpaId}">
          <DataGridTextColumn.Header>
               <TextBlock  Style="{StaticResource
                                  DataGridHeader}">
                    Impa
               </TextBlock>
          </DataGridTextColumn.Header>
          <DataGridTextColumn.ElementStyle>
              <Style TargetType="{x:Type TextBlock}">
                  <Setter Property="HorizontalAlignment" Value="Right" />
              </Style>
          </DataGridTextColumn.ElementStyle>
      </DataGridTextColumn>