21

I want to know how to get the DataGridCell from DataGridCellInfo. Actually i have a some selected cells in datagrid, and SelectedCells property return DataGridCellInfo's collection, but i want to change the background of those cells at runtime too. so i need the datagrid cell.

kindly suggest me how to do so and also how to change the datagrid cell background color dynamically(through code) also.

Thanks

manav inder
  • 3,531
  • 16
  • 45
  • 62
  • If you do it with XAML is way simpler, i advice. – Natxo Nov 08 '11 at 10:21
  • Thanks, but actually i am developing a custom control, so i need a more generic approach for this – manav inder Nov 08 '11 at 10:29
  • 1
    Well, take a look at the answer of the question: http://stackoverflow.com/questions/1764498/wpf-datagrid-programmatically-editing-a-cell [1]: http://stackoverflow.com/questions/1764498/wpf-datagrid-programmatically-editing-a-cell – Natxo Nov 08 '11 at 10:33
  • Thanks a lot, it works but only for the partial question, i still not get the part to set the background color dynamically – manav inder Nov 08 '11 at 11:00

2 Answers2

54

To anyone who got here from a search engine, expecting to find an answer to the title in the question, look here: https://stackoverflow.com/a/17066695/937093

Content:

public DataGridCell GetDataGridCell(DataGridCellInfo cellInfo)
{
    var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
    if (cellContent != null)
        return (DataGridCell) cellContent.Parent;

    return null;
}

edit

if you upvote this answer please don't forget to upvote the original answer I linked as well!

Community
  • 1
  • 1
Steffen Winkler
  • 2,805
  • 2
  • 35
  • 58
  • @user3690202 not really. The problem with this question is that what is asked in the title is different from what is asked in the question itself. The marked answer does answer the question manav inder really had. – Steffen Winkler Jul 17 '15 at 08:50
  • 1
    If the cell is not in view, we need to use `Datagrid.ScrollIntoView`. – nan Jan 29 '16 at 07:24
5

To change the color of the cell dynamically this is the simplest way

cell.Background = new SolidColorBrush(Colors.Green);

and to get the datagrid cell, follow this link

WPF Datagrid: Programmatically editing a cell

Thanks to Natxo

Community
  • 1
  • 1
manav inder
  • 3,531
  • 16
  • 45
  • 62