nerdalert
nerdalert

Reputation: 461

C# WPF datagrid row background color

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.

Upvotes: 1

Views: 10864

Answers (1)

mm8
mm8

Reputation: 169150

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.

Upvotes: 1

Related Questions