3
votes

I want to change the color of the cell in a datagrid when the user changes the text or content of that cell.

I am using WPF an C#.

I have a simple datagrid:

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

This events: keydown and selectedcellschange are tests for change my color cell. In the .cs I tried changing the cel.... but I failed.

I need an event that is released when the content changes

2
What have you tried so far? Show some code. Check this metaSO question and Jon Skeet: Coding Blog on how to write and ask a good question.Yaroslav
Add your code on the question, not as a comment. Use the edit link on the lower left corner of the question, below the tags list.Yaroslav

2 Answers

0
votes

Set a behavior, the easiest way is using Blend. I provide an example against a datagrid on my blog article: Xaml: Adding Visibility Behaviors Using Blend to A DataGrid for WPF or Silverlight

0
votes

Resolved:

 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();

    }

When the user finishes editing the cell turns red.

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