Tip:Changing Foreground on row selection in Datagrid

When we want to change the foreground of the cells in datagrid when the row is selected it seems easier to write a few lines of code than messing with the templates
In the selectionchanged handler, we can loop throgh the columns and set the foreground of each cell like below

void datagrid2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (DataGridColumn col in datagrid2.Columns)
{
FrameworkElement ele = col.GetCellContent(e.AddedItems[0]);
(ele as TextBlock).Foreground = new SolidColorBrush(Colors.Blue);
if (e.RemovedItems.Count > 0)
{
ele = col.GetCellContent(e.RemovedItems[0]);
(ele as TextBlock).Foreground = new SolidColorBrush(Colors.Black);
}
}
}

Advertisements

15 thoughts on “Tip:Changing Foreground on row selection in Datagrid

  1. Thank you. This is wonderful idea.

    Issues:

    1. if several rows are selected: a. pressing up arrow causes indexoutofrange exception since AddedItems collection is empty.
    b. only first item color is restored
    2. If DataGrid contains checkbox or custom templates, casting to TextBlock fails. For this we need to add DisplayElementName to custom template.
    Fixed code:

    FrameworkElement frameWorkelement;
    TextBlock textBlock;
    foreach (DataGridColumn col in _parentGrid.Columns)
    {
    foreach (var item in e.AddedItems)
    {
    frameWorkelement = col.GetCellContent(item);
    textBlock = frameWorkelement.FindName(“DisplayElement”) as TextBlock;
    if (textBlock != null)
    {
    textBlock.Foreground = new SolidColorBrush(Colors.Blue);
    }
    }

    foreach (var item in e.RemovedItems)
    {
    frameWorkelement = col.GetCellContent(item);
    textBlock = frameWorkelement.FindName(“DisplayElement”) as TextBlock;
    if (textBlock != null)
    {
    textBlock.Foreground = new SolidColorBrush(Colors.Black);
    }
    }
    }

    How to use this method to keep background of selected rows ? TextBlock does not have BackGround property.

    Andrus.

    1. you might have to use templatecolumn and wrap the element in Grid or something, which has background color in the cellTemplate
      you can try chechking for null before accessing ADdedItems/RemovedItems.
      one idea might be change the template of the DataGridRow( did not try it myself), or have a custom datagridrow where you can specify the background color

      1. OK, setting bakground seems to be doable. But in editable DataGrid if Tab key is pressed, color changes made by your code is lost since cell is re-drawn. How to fix this so that your code can be used ? I’m thinking about adding “bool IsSelected” property on every entity and use Converter to change backcolor instead of your code. How to make color changes done by this code permant so thaey are not lost on tabbing in row ?

  2. Using this and pressing Ctrl+Up arrow and Ctrl+Down arrow keys in DataGrid when there are more that one pane of rows sets foreground color to multiple lines. How to fix this ?

          1. No. How to turn virtualization off ? It occurs also in ctrl+home/ctrl+end is pressed multiple times. 1-3 rows in top and in bottom of screen have wrong color in most columns.
            I’m looking for a way to highlight selected row but also allow yellow background for posted invoices.
            I changed DataGrid row style rectange fill to Fill=”{Binding Converter={StaticResource IndexToBrushConverter}, Mode=OneWay}”

            After that error occurs in line –>

            about missing Fill property. So using custome background is also not possible.

          2. try turning off virtualization by changing the template of the datagrid
            wrap DataGridRowsPresenter in a scrollviewer, it will be a bit slower, but will work correctly

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s