Home > Mobile >  How to change the appearance of a row within a DataGrid, based on the value of a cell, in WPF?
How to change the appearance of a row within a DataGrid, based on the value of a cell, in WPF?

Time:09-23

As I'm new in C# WPF, I tried to give it a go, using the trial-and-error approach.

What I would like to do, is to change the appearance of a row in a DataGrid, based on some user action.
However, from reading information over the internet, I've understood that the "right" way to go is:

You should not write a method or a function: you need to write an event.

Okay, okay, so I started doing this in the XAML:

<DataGrid x:Name="dg_Areas" ... LoadingRow="View_dg_Areas"/>

Apparently, the View_dg_Areas event handler should have following signature:

private void View_dg_Areas(object sender, DataGridRowEventArgs e) { }

But then what?

I started, very naïvely, as follows:

private void View_dg_Areas(object sender, DataGridRowEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.ToString());
    System.Diagnostics.Debug.WriteLine(e.Row.ToString());
    System.Diagnostics.Debug.WriteLine(e.Row.Item.ToString());
}

The idea was to learn from this how I can find information of the corresponding row (is there a way to read the value of a certain column?), but I didn't get anywhere.

I can tell you that the DataGrid is linked to a DataTable, as follows:

dg_Areas.ItemsSource = dataSet.Tables["Areas"].DefaultView;

How can I link the event parameter e and the DataTable the DataGrid is representing?

CodePudding user response:

You could use a RowStyle with a DataTrigger that binds to one of your properties or columns:

<DataGrid x:Name="dg_Areas">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding YourColumn}" Value="SomeValue">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

The above sample markup changes the background colour of the rows where "YourColumn" equals "SomeValue".

Using XAML defined styles to change the visual appearance is considered a best practice. Handling events is not.

  • Related