2
votes

I have a DataGrid control bound to an ItemsSource. My ItemsSource is an ObservableCollection and it and I always insert my items ordered on it. I need to set the background of each row of the DataGrid depending on the value and its index on the DataGrid. Do you know any way to do that? Note: the ObservableCollection will be updated by another thread, so when it updates, I have to update the background color of the grid.

I've seen some people doing things similar using a converter, but all my business logic is in the ViewModel and I need to get values from it to discover wich color will be the background.

Thanks in advance.

1

1 Answers

1
votes

You could add a LoadingRow event handler to your DataGrid, and then setup a binding to each row's Background property on their respective item's view model property:

XAML DataGrid:

<data:DataGrid ItemsSource="{Binding FooBars}" LoadingRow="dataGrid_LoadingRow" >
    <data:DataGrid.Columns>
        <data:DataGridTextColumn Header="FOO" Binding="{Binding Foo}" Width="200" />
        <data:DataGridTextColumn Header="BAR" Binding="{Binding Bar}" Width="60"/>
    </data:DataGrid.Columns>
</data:DataGrid>

Code-behind:

private void packetsDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    Binding backgroundBinding = new Binding("FooBarItemBackground");
    backgroundBinding.Source = e.Row.DataContext;
    e.Row.SetBinding(DataGridRow.BackgroundProperty, backgroundBinding);
}