2012-04-07 169 views
6

我有一個充滿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? 
} 

如何在啓動和運行時訪問行?

回答

11

使用RowStyle。您可以使用Triggers來有條件地更改顏色,或者僅將其綁定到項目上的Brush屬性並分別更改該屬性。

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