Mr Rampage
The Rampage

The Rampage

WPF DataGrid RowStyle right border fix

Mr Rampage's photo
Mr Rampage

Published on Mar 24, 2021

2 min read

Styling components in WPF (and CSS for that matter) is a pain. Sometimes you try to do something so trivial and the framework just wants to fight you. Today I had a simple task:

Given an invalid data, create a red border around the row with the error.

This data set was implemented using DataGrids. A simple RowStyle and DataTrigger was all I needed. This was the simple implementation in XAML:

...
<DataGrid.RowStyle>
  <Style TargetType="{x:Type DataGridRow}" 
    BasedOn="{StaticResource {x:Type DataGridRow}}">
    <Setter Property="BorderBrush" Value="Transparent" />
    <Setter Property="BorderThickness" Value="1" />
    <Style.Triggers>
      <DataTrigger Binding="{Binding IsValid}" Value="False">
        <Setter Property="BorderBrush" Value="Red" />
      </DataTrigger>
    </Style.Triggers>
  </Style>
</DataGrid.RowStyle>
...

Pretty straight forward, eh? Not really, because no matter what I did, the right side of the border got truncated. After several hours of hacking around and research, the fix turned out to be negative margins on the DataCellPresenter.

...
  <Style TargetType="{x:Type DataGridRow}" 
    BasedOn="{StaticResource {x:Type DataGridRow}}">
    <Style.Resources>
      <Style BasedOn="{StaticResource {x:Type DataGridCellsPresenter}}"
        TargetType="{x:Type DataGridCellsPresenter}">
        <Setter Property="Margin" Value="-1" />
      </Style>
    </Style.Resources>
...

Oddly, if the same requirement was done for the DataGrid.CellStyle this issue wouldn't happen. It appears to only affect DataGrid.RowStyle. Styling is hard and it's equally hard to create a styling engine without all sorts of weird edge cases. In this case, a literal edge case. Hopefully, this helps some future Internet explorer!

 
Share this