2012-11-06 65 views
3

當用戶更改該單元格的文本或內容時,我想更改數據網格中單元格的顏色。當文本更改時,WPF數據網格更改顏色

我正在使用WPF的C#。

我有一個簡單的數據網格:

<DataGrid x:Name="dataGrid1" Grid.RowSpan="2" Margin="5" ItemsSource="{Binding Source=Horreos}" KeyDown="dataGrid1_KeyDown" SelectedCellsChanged="dataGrid1_SelectedCellsChanged"> <DataGrid.Columns > </DataGrid.Columns> </DataGrid> 

此事件:KeyDown和selectedcellschange是改變我的一個色彩單元測試。在.cs中,我試着改變了cel ......但是我失敗了。

我需要當內容發生變化

+0

你嘗試過這麼遠嗎?顯示一些代碼。檢查這個[metaSO問題](http://meta.stackexchange.com/questions/18584/how-to-ask-a-smart-question)和[Jon Skeet:Coding Blog](http://msmvps.com/ blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx)如何撰寫和提出一個好問題。 – Yaroslav

+0

在問題上添加您的代碼,而不是評論。使用問題左下角的** edit **鏈接,位於標籤列表下方。 – Yaroslav

回答

0

解決:

private void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
    { 
     DataGridCell gridCell = null; 
     try 
     { 
      gridCell = GetCell(dataGrid1.SelectedCells[0]); 
     } 
     catch (Exception) 
     { 
     } 
     if (gridCell != null) 
      gridCell.Background = Brushes.Red; 

    } 
public DataGridCell GetCell(DataGridCellInfo dataGridCellInfo) 
    { 
     if (!dataGridCellInfo.IsValid) 
     { 
      return null; 
     } 

     var cellContent = dataGridCellInfo.Column.GetCellContent(dataGridCellInfo.Item); 
     if (cellContent != null) 
     { 
      return (DataGridCell)cellContent.Parent; 
     } 
     else 
     { 
      return null; 
     } 
    } 

private void MyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e) 
    { 
     DataGrid grid = sender as DataGrid; 
     e.Row.MouseEnter += (s, args) => Row_MouseEnter(s, grid); 
     e.Row.MouseLeave += (s, args) => Row_MouseLeave(s, grid); 
    } 

    void Row_MouseLeave(object sender, DataGrid grid) 
    { 
     DataGridRow row = sender as DataGridRow; 
     grid.SelectedIndex = -1; 
    } 

    void Row_MouseEnter(object sender, DataGrid grid) 
    { 
     DataGridRow row = sender as DataGridRow; 
     grid.SelectedIndex = row.GetIndex(); 

    } 

當用戶完成編輯單元格變爲紅色。

<DataGrid x:Name="dataGrid1" Grid.RowSpan="2" SelectionUnit="CellOrRowHeader" 
        Margin="5" ItemsSource="{Binding Source=Source}" LoadingRow="MyDataGrid_LoadingRow" CellEditEnding="dataGrid1_CellEditEnding"> 
      <DataGrid.Columns>