更改WPF Datagrid行颜色
问题描述:
我有一个充满ObserverableCollection的WPF数据网格。更改WPF Datagrid行颜色
现在我想根据程序启动时的行内容对行进行着色,如果在运行时发生了某些变化。
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列,看它是否大于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
{
}
}