gpt4 book ai didi

c# - datagrid 获取单元格索引

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:36 27 4
gpt4 key购买 nike

是否可以获取列标题 = "column4"且行包含 "232"的单元格索引例如我上传的屏幕截图是否有可能获得红细胞指数而不是让它变成红色?如果 wpf datagrid 有那个功能 wpf toolkit data grid 有吗?列和行是从 enter image description here 后面的代码添加的

最佳答案

您应该通过 Style/TriggerBinding 使用转换器来完成此操作

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

关于c# - datagrid 获取单元格索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com