2012-11-06 64 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>