更改WPF Datagrid行颜色

时间:2012-04-07 17:25:40

标签: c# wpf datagrid colors row

我有一个用ObserveableCollection填充的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?
}

如何在开始和运行时访问行?

2 个答案:

答案 0 :(得分:12)

使用RowStyle。您可以使用Triggers有条件地更改颜色,或者只是将其绑定到商品的Brush属性并分别更改该属性。

答案 1 :(得分:5)

要通过代码而不是触发器来更改它,它可能看起来像下面的内容。您可以将数据作为数组访问,然后进行比较。在这个例子中,我比较第4列以查看它是否大于0和第5列以查看它是否小于0否则只是将其绘制为默认颜色。尝试/捕获它有一些逻辑需要添加,看看它是否是一个有效的行.....或者你可以忽略下面的错误(虽然不是很好的做法)但应该可以使用

    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
        {
        } 
    }
相关问题