简体   繁体   中英

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?

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.

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
        {
        } 
    }

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