Home > Silverlight > Tip:Changing Foreground on row selection in Datagrid

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

Categories: Silverlight
  1. Fallon Massey
    January 7, 2009 at 2:32 am | #1

    Nice on Lee.

  2. Fallon Massey
    January 7, 2009 at 2:32 am | #2

    Should be…

    Nice one Lee.

  3. alejandrobog
    July 4, 2009 at 5:58 am | #4

    Its not that hard to do it with templates.
    You can wrap the DataGridCellPresenter into a ContentControl and modify its properties.

    Here is how:

    http://alejandrobog.wordpress.com/2009/07/02/silverlight-datagrid-change-foreground-color-on-visualstatemanagermouseover-selected/

  1. No trackbacks yet.