I want to select multiple cells of a datagrid from code behind. My input to the function is a
List<Tuple<int,int>>
which contains the positions of all the cells I want to highlight in row,column format.
Basically, I want to highlight it in such a way such that any previously selected cells are unselected and the cells in the input list are selected.
It would also be nice if the
SelectedCellsChanged
event is fired. I dont care if it fired multiple times also.
I am unable to find any examples of this
Please help.
-------------------- Added your code from your comment -------
basically i know how to change the background colour of the cell. I can get the cell using this method (already using this), you can ignore the highlight flag stuff as it is specific to my app.
public void ColourCell(int row, int column, Color color, bool HighlightFlag = true)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild(rowContainer);
DataGridCell cell =
(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (HighlightFlag == false)
cell.Background = new SolidColorBrush(Colors.MediumPurple);
else
{
cell.Background = new SolidColorBrush(color);
}
}
}
public DataGridRow GetRow(int index)
{
DataGridRow row =
(DataGridRow)DataGridControl.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
row = (DataGridRow)DataGridControl.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
static T GetVisualChild(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild(v);
}
if (child != null)
{
break;
}
}
return child;
}