1
votes

I have the below simplified code to color certain rows of my DataGrid. I would like to do this task programmatically and not through XAML.

public IEnumerable<System.Windows.Controls.DataGridRow> GetDataGridRows(System.Windows.Controls.DataGrid grid)
{
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as System.Windows.Controls.DataGridRow;
        if (null != row) yield return row;
    }
}

public void color()
{
    var rows = GetDataGridRows(dg1);

    foreach (DataGridRow r in rows)
    {
        //DataRowView rv = (DataRowView)r.Item;

        //remove code for simplicity

        r.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 100, 100, 100));
    }
}

Doing this does not change the background of the row.

1
Why doing this via code if there are better and easier ways doing it in xaml?Mighty Badaboom
I already have the function working in Winforms, so I am trying to directly convert it. I'm sure its an easy fix in my code above, one that im not seeing.nerdalert
I would recommend using xaml for this because WPF isn't winforms and the way you should develop WPF is different then winforms. Just my two centsMighty Badaboom
Do you want to change the row color depending on the content of a certain cell-value?user7220101
Basically I want to compare two datagrids, each with one column, and change the row color of rows that are not in the other datagrid.nerdalert

1 Answers

1
votes

This won't work unless you display very few rows in your DataGrid or disable the UI virtualization (which of course may lead to performance issues).

The correct way do change the background colour of the rows in a DataGrid in WPF is to define a RowStyle, preferably in XAML:

<DataGrid x:Name="grid">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="#64646464" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

Trying to just "convert" your Windows Forms code as-is is certainly a wrong approach. WPF and Windows Forms are two different frameworks/technologies and you don't do things the same way in both. Then it would be pretty much useless to convert in the first place.