Datagrid get cell index

Is it possible to get the index of a cell where the column heading = "column4" and the row contains "232" for example, a downloaded screenshot allows you to get the index of red cells and make it red? and if the wpf datagrid has this function, does the wpf toolkit data grid have? columns and rows are added from the code for enter image description here

0
source share
1 answer

You must do this via Style / Trigger or Binding with a type converter

 <DataGrid Name="dataGrid" ...> <DataGrid.Columns> <DataGridTextColumn Header="column4" Binding="{Binding column4}"> <DataGridTextColumn.CellStyle> <Style TargetType="DataGridCell"> <Style.Triggers> <DataTrigger Binding="{Binding column4}" Value="232"> <Setter Property="Background" Value="Red"/> </DataTrigger> </Style.Triggers> </Style> </DataGridTextColumn.CellStyle> </DataGridTextColumn> <!--...--> </DataGrid.Columns> <!--...--> </DataGrid> 

By default, the DataGrid uses virtualization, so only those DataGridRows that are currently visible to the user are loaded. Other lines will be created after they become visible, so if you try to style some cells in the code behind, it can become quite dirty (the cell you are trying to access may not even exist.)

To get a DataGridCell in an index row / column, you can define a helper class ( DataGridHelper ) and use it as follows

 DataGridCell cell = DataGridHelper.GetCell(dataGrid, 0, 2); if (cell != null) { cell.Background = Brushes.Red; } 

DataGridHelper

 static class DataGridHelper { static public DataGridCell GetCell(DataGrid dg, int row, int column) { DataGridRow rowContainer = GetRow(dg, row); if (rowContainer != null) { DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); // try to get the cell but it may possibly be virtualized DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); if (cell == null) { // now try to bring into view and retreive the cell dg.ScrollIntoView(rowContainer, dg.Columns[column]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); } return cell; } return null; } static public DataGridRow GetRow(DataGrid dg, int index) { DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); if (row == null) { // may be virtualized, bring into view and try again dg.ScrollIntoView(dg.Items[index]); row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); } return row; } static T GetVisualChild<T>(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<T>(v); } if (child != null) { break; } } return child; } } 
+7
source

All Articles