Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a DataGrid cellstyle based on the previous row value

Tags:

wpf

datagrid

In a DataGrid - Is there a way to set a cell style based on the value of the cell in the previous row?

like image 245
Phil Boyd Avatar asked Dec 07 '25 08:12

Phil Boyd


1 Answers

During binding, you can access the prior value in the collection by accessing the RelativeSourceMode Enumeration. Specifically, RelativeSource PreviousData.

The string token PreviousData; corresponds to a RelativeSource as created with its Mode property set to PreviousData.

Here's an example I used when creating a comma separated list of items in XAML and ensuring the last value does not contain a trailing comma:

<DataTemplate>
    <TextBlock FontFamily="Segoe Print">
        <TextBlock x:Name="Comma" Text="," />
        <TextBlock Text="{Binding}" />
    </TextBlock>

    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}">
            <Setter TargetName="Comma" Property="Visibility" Value="Collapsed" />
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>
like image 74
Metro Smurf Avatar answered Dec 09 '25 04:12

Metro Smurf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!