改变 WPF 数据表格行的颜色

10

我有一个使用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?
}

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

2个回答

12

使用 RowStyle。您可以使用Triggers有条件地更改颜色,或者只需将其绑定到项目上的 Brush 属性并相应更改该属性。


10
要通过代码而不是触发器更改它,代码应如下所示。您可以将数据访问为数组,然后进行比较。在此示例中,我正在比较第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
        {
        } 
    }

如何使用加载事件方法? - Klasik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接