Changing Foreground of cells that are modified in DataGrid

Lets say you have a DataGrid in a page and want to show the cells with changed values as in this forum post.

Before edit

after edit

here is one way. (It wont work with DataGrid with Scrollbars)

Sample xaml

<UserControl xmlns:data=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”
    <Grid x:Name=”LayoutRoot”
        <data:DataGrid x:Name=”grid1″
                <data:DataGridTextColumn Width=”100″
                                         Binding=”{Binding FirstName}”>

                <data:DataGridTextColumn Header=”LastName”
                                         Binding=”{Binding LastName}”></data:DataGridTextColumn>
                <data:DataGridTextColumn Header=”HomeTown”
                                         Binding=”{Binding HomeTown}”></data:DataGridTextColumn>


 public Page()
            grid1.ItemsSource = new People();
            grid1.PreparingCellForEdit += new EventHandler<DataGridPreparingCellForEditEventArgs>(grid1_PreparingCellForEdit);
            grid1.CurrentCellChanged += new EventHandler<EventArgs>(grid1_CurrentCellChanged);

        void grid1_CurrentCellChanged(object sender, EventArgs e)
            if (column != null && row != null)
                TextBlock textBlock = (column.GetCellContent(row) as TextBlock);
                textBlock.Foreground = new SolidColorBrush(Colors.Blue);
                row = null;
                column = null;

        DataGridRow row;
        DataGridColumn column;
        void grid1_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
            column = e.Column;
            row = e.Row;          

When the cell is getting ready to be edited we save the row and column and when the current cell changes we get the CellContent (usually a TextBlock, unless you are showing something different or have a CellTemplate)  and change the Foreground. Finally reset our variables


5 thoughts on “Changing Foreground of cells that are modified in DataGrid

    1. Hi,
      You would need something on the data object that you bind to tell if that is changed. when you scroll, loadingrow and unloadingrow events are raised. you would need to check the property on the object and change the foreground accordingly.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s