Change WPF Datagrid Row Color

29,087

Solution 1

Use the RowStyle. You can use the Triggers to change the color conditionally, or just bind it to a Brush property on your items and change that property respectively.

Solution 2

To change it through code instead of a trigger it could look something like below. You can access the data as an array and then compare it. In this example I am comparing the 4th column to see if it is greater than 0 and the 5th column to see if it is less than 0 otherwise just paint it the default color. The try/catch it there becuase some logic needs to be added to see if it is a valid row or not.....or you can just ignore the errors as below (not really good practice though) but should be usable as is.

    private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        try
        {
            if (Convert.ToDouble(((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[3].ToString()) > 0)
            {
                e.Row.Background = new SolidColorBrush(Colors.Green);
            }
            else if (Convert.ToDouble(((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[4].ToString()) < 0)
            {
                e.Row.Background = new SolidColorBrush(Colors.Red);
            }
            else
            {
                e.Row.Background = new SolidColorBrush(Colors.WhiteSmoke);
            }
        }
        catch
        {
        } 
    }
Share:
29,087
juergen d
Author by

juergen d

Updated on July 09, 2022

Comments

  • juergen d
    juergen d almost 2 years

    I have a WPF datagrid that is filled with an ObserverableCollection.

    Now I want to color the rows depending on the row content at the program start and if something changes during runtime.

    System.Windows.Controls.DataGrid areaDataGrid = ...;
    ObservableCollection<Area> areas;
    //adding items to areas collection
    areaDataGrid.ItemsSource = areas;
    
    areaDataGrid.Rows  <-- Property not available. how to access rows here?
    
    CollectionView myCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(areaDataGrid.Items);
    ((INotifyCollectionChanged)myCollectionView).CollectionChanged += new NotifyCollectionChangedEventHandler(areaDataGrid_Changed);
    ...
    
    void areaDataGrid_Changed(object sender, NotifyCollectionChangedEventArgs e)
    {
        //how to access changed row here?
    }
    

    How can I access the rows at start and runtime?

  • Klasik
    Klasik about 4 years
    how to use loading event method?