8

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

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

4

2 回答 2

12

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

于 2012-04-07T17:29:50.077 回答
7

要通过代码而不是触发器来更改它,它可能如下所示。您可以将数据作为数组访问,然后进行比较。在此示例中,我将比较第 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
        {
        } 
    }
于 2012-11-30T04:14:09.510 回答