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

wpf datagrid column alignment programmatically
wpf datagrid datagridtextcolumn horizontal alignment
wpf datagrid cell vertical content alignment
wpf datagrid add row
wpf datagrid column width fill
wpf datagrid column header alignment
wpf datagrid summary row
wpf datagrid template

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.

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

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}">

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> 

xaml, 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  Is there a way to make the white area not covered by a cell clickable? My intention: I want to have full row selection. This can be achieved by SelectionUnit="FullRow" which is fine but how can I make the white area implicitly select the entire row without expanding available cells in width and avoiding code behind. Here is the repro code: Xaml:

Just wanted to add to more examples for future code searches.

I put this in the top of the xaml file:

<UserControl.Resources>
    <Style TargetType="{x:Type TextBlock}" x:Key="RightCell">
        <Setter Property="Background" Value="{Binding Included, Converter={StaticResource BoolToColorConverter}}"/>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="TextAlignment" Value="Right"/>
    </Style>
</UserControl.Resources>

And then in the datagrid:

<DataGridTextColumn Header="Excluded" Binding="{Binding Excluded}" ElementStyle="{StaticResource RightCell}"/>

This right aligns the text and sorting is still enabled. The textbox fills the cell and in this case is colored using a bool converter.

Wpf datagrid row height auto, Set this property to NaN ("Auto" in XAML) to make the row automatically can right-align or centre the text in a DataGridRowHeader in a DataGrid in WPF 2011 · While developing silverlight data grid when we select a row then the The following code snippet sets column width and row height to 100 and 30 respectively. 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. If I remove the CellStyle, the area works as desired but of course I lose the right alignment.

I just had a similar problem and found another solution by overwriting the Style for the DataGridCell in Blend.

The changed items from the original style are the setters for VerticalAlignment and VerticalContentAlignment in the Style itself to stretch the cell itself and VerticalAlignment="Center" and HorizontalAlignment="Right" in the Template property to align the content. Change these values to whatever you need to align the cells content.

The rest of the style could be removed so that the settings from the base style will be used (using the StaticResource the style is BasedOn). However I left the style as Blend produced it.

This resulting XAML-Code should then be included into the controls resources:

<Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource ResourceKey={x:Type DataGridCell}}">
    <Setter Property="VerticalAlignment" Value="Stretch" />
    <Setter Property="VerticalContentAlignment" Value="Stretch" />

    <!-- Additional styles, can be removed to fall back to base styles -->
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                    <ContentPresenter
                        ContentTemplate="{TemplateBinding ContentTemplate}"
                        Content="{TemplateBinding Content}"
                        ContentStringFormat="{TemplateBinding ContentStringFormat}"
                        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                        VerticalAlignment="Center"
                        HorizontalAlignment="Right"
                        />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
            <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
        </Trigger>
        <Trigger Property="IsKeyboardFocusWithin" Value="True">
            <Setter Property="BorderBrush" Value="{DynamicResource {ComponentResourceKey ResourceId=FocusBorderBrushKey, TypeInTargetAssembly={x:Type DataGrid}}}"/>
        </Trigger>
    </Style.Triggers>
</Style>

The DataGrid control, An introduction to the WPF DataGrid control, with a simple example to get you You can start using the DataGrid without setting any properties, because it the column headers - you will see that the DataGrid supports sorting right out The last and empty row will let you add to the data source, simply by filling out the cells. When i click right mouse button it shows int value correctly. But in my GetValue(object data) function console return null at first right click and from second time returns int value, but value in console is always diferent from textblock value, i have to click two times on same cell to get right cell position. That is completly wrong.

You can try a work around :

           <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Grid Background="White" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                        <TextBlock HorizontalAlignment="Right" Text="{Binding Path=ImpaId}"/>
                    </Grid>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

C# Windows Forms, DataGrid (dgr) - Allows the user to display (and edit) a table of information. If you want to select a row programmatically and if the datagridview is on a The DataGridView control can have several different types of columns You can sort this column programmatically; however, it is not intended for sorting, so no space is  The WPF DataGrid is a very flexible tool, however in its current state certain simple tasks can prove to be rather tricky. A fairly common task when working with DataGrid is detecting which row, or cell a user has clicked on, or whether they clicked a column header.

I had the same issue and got it solved now. If you want to do it inside the c# code, you need to set a bunch of setters:

DataGridTextColumn numColumn = new DataGridTextColumn
Style s = new Style();
s.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
s.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Right));
s.Setters.Add(new Setter(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
s.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
numColumn.CellStyle = s;

Conditional Styling in WPF DataGrid control, CellStyleSelector property and the particular column record cells can be customized by setting GridColumn.CellStyleSelector property and you can get the  This article provides an example of how you can right-align or centre the text in a DataGridRowHeader in a DataGrid in WPF using Visual Studio 2012 or later. It also explains how you can display the correct row numbers in the DataGridRowHeader and automatically update these as you are adding or removing items to and from the DataGrid’s

ASP.NET MVC Grid control example - Demos, Column menu, resizing, reordering and show/hide Interactions You can find additional information on how to use the ASP. HeaderHtmlAttributes(new { @​class = "checkbox-align" }); columns. Selection("continuous") . img { margin-​right: 10px; } #grid .k-grid-edit-row > td > .k-rating No data found. You have to override Template of Groupbox in case you want to align header to Right. By default it is placed at left in default template.

The Baker's Dozen: 13 Productivity Tips for the Windows Forms , The new grid class makes life a little simpler when it comes to defining columns. Of course, you can't get very far without creating some test data. Column Alignment (Left, Center, or Right); Read only (True or False); Any special formatting CurrentCell = new DataGridCell(hti.Row, hti.Column); this.Select(hti.​Row); }. In the option, you have both options for selection individual cell or selection of full row. <DataGrid x:Name="myDataGrid" SelectionUnit="CellOrRowHeader"> </DataGrid> In the above screenshot, In second row I have selected single column and In the third row, I have selected full row. Row Header is the very first column in the WPF DataGrid.

WPF DataGrid Custommization using Style and Template , Step 1 : Create style of TargetType=DatagridColumnHeader Column="1" ItemsPanel="{TemplateBinding ItemsPanel}" Step 3: Now, Add VisualState for Setting DataGridRow Background I have created this style for hide the default datagrid row selected color (Blue). But i play little bit another style.

Comments
  • Similar problem but don't know the answer: stackoverflow.com/questions/18378515/…
  • I was able to minimize the code by just adding the ElementStyle property at the outer DataGridTextColumn and have it use my existing CellRightAlign. Thanks.
  • Perfect and simple "ElementStyle" assignment.