Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change WPF Datagrid Row Color

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?

like image 617
juergen d Avatar asked Apr 07 '12 17:04

juergen d


2 Answers

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.

like image 116
H.B. Avatar answered Sep 30 '22 06:09

H.B.


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
        {
        } 
    }
like image 36
itman Avatar answered Sep 30 '22 07:09

itman