是否可以获取列标题=“column4”且行包含“232”的单元格索引 例如,我上传的屏幕截图是否有可能获得红细胞索引,而不是让它变成红色?如果wpf datagrid有那个函数,wpf工具包数据网格有吗?列和行是从
后面的代码添加的答案 0 :(得分:8)
您应该通过Style
/ Trigger
或Binding
使用转换器
<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>
默认情况下,DataGrid
正在使用虚拟化,因此只会加载此时用户可见的DataGridRows
。其他行将在可见后创建,因此如果您尝试在后面的代码中设置一些单元格可能会变得非常混乱(您尝试访问的单元格可能甚至还不存在。)
要在索引行/列处获得DataGridCell
,您可以定义一个帮助程序类(DataGridHelper
)并像这样使用它
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;
}
}