更改WPF DataGrid行的颜色(Change WPF Datagrid Row Color)

2019-06-23 10:40发布

我有一个充满ObserverableCollection一个WPF数据网格。

现在,我要的颜色取决于在节目开始的行内容的行,如果在运行时有新的变化。

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

如何访问在启动和运行时的行?

Answer 1:

使用RowStyle 。 您可以使用Triggers有条件地改变颜色,或只是将其绑定到一个Brush上您的物品属性分别更改属性。



Answer 2:

要想改变它通过代码,而不是触发它可能看起来像下面的。 您可以访问数据作为一个数组,然后进行比较。 在这个例子中,我比较第4列,看它是否大于0,看到第5列,如果是小于0,否则只是画它的默认颜色。 该try / catch语句它有监守一些逻辑需要添加,看它是否是一个有效的行或不.....或者你可以忽略这些错误如下(虽然不是很好的做法),但应可作为是。

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


文章来源: Change WPF Datagrid Row Color