简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM