c# - 自动 DataGridView 单个单元格的前景
问题描述
我试图在 DataGridView 的一行中设置单个单元格的前景,但我找不到答案。该函数加载所有 DataGrid 并在找到“Alta”时更改前景,但如果我更改 DataGrid 的顺序(如按名称排序),前景再次变为默认值。这里的功能:
private void DataGrid_Color(DataGrid Grid)
{
Grid.UpdateLayout();
foreach (DataRowView item in Grid.ItemsSource)
{
if (item.Row[7].Equals("Alta"))
{
Grid.UpdateLayout();
DataGridRow row = (DataGridRow)Grid.ItemContainerGenerator
.ContainerFromItem(item);
DataGridCell column = Grid.Columns[7].GetCellContent(row)
.Parent as DataGridCell;
if (row != null)
{
column.Foreground = Brushes.Red;
}
}
else if (item.Row[7].Equals("Média"))
{
Grid.UpdateLayout();
DataGridRow row = (DataGridRow)Grid.ItemContainerGenerator
.ContainerFromItem(item);
DataGridCell column = Grid.Columns[7].GetCellContent(row)
.Parent as DataGridCell;
if (row != null)
{
column.Foreground = Brushes.Orange;
}
}
else if (item.Row[7].Equals("Baixa"))
{
Grid.UpdateLayout();
DataGridRow row = (DataGridRow)Grid.ItemContainerGenerator
.ContainerFromItem(item);
DataGridCell column = Grid.Columns[7].GetCellContent(row)
.Parent as DataGridCell;
if (row != null)
{
column.Foreground = Brushes.Green;
}
}
Grid.UpdateLayout();
}
}
我尝试其他功能,每行加载行但返回 null
private void dgv_LoadingRow(object sender, DataGridRowEventArgs e)
{
if (ativo && coluna != -1)
{
DataRowView dataRowView = e.Row.Item as DataRowView;
if (Convert.ToString(dataRowView[coluna]).Equals("True"))
{
e.Row.BorderBrush = Brushes.Gray;
e.Row.BorderThickness = new Thickness(1);
}
else
{
e.Row.BorderBrush = Brushes.Gray;
e.Row.BorderThickness = new Thickness(1, 0, 1, 0);
}
}
}
我有其他方法可以更改 DataGrid 中的单个单元格前景并且不返回 null 或将前景恢复为默认值?
解决方案
您可以为要在不同条件下设置前景的列设置 DataGridRow 样式,如下所示:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Name}" Value="Alta">
<Setter Property="Foreground" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Name}" Value="Média">
<Setter Property="Foreground" Value="Orange"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Name}" Value="Baixa">
<Setter Property="Foreground" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
推荐阅读
- javascript - 如何让 JavaScript 按钮调用新的 Firebase (v9.0.0+) signInWithPopup
- python - python:将csv文件转换为json格式并尝试调用数据中没有另一列的列
- go - 无法在 Golang 中返回值
- ios - CoreData+CloudKit 集成问题
- sql - 如何从 SQL 中以逗号存储的 id 获取名称
- crystal-reports - Crystal Reports - 如何制作一组数组以在气泡图中使用?
- google-api - 如何获取 out-of-office/VacationSettings start/endTime 的时区信息?
- c# - ILogger 未在 DebugView 中显示
- angular - OnSaveSucces 页面重定向
- spring-boot - 关闭 application.properties 文件中的日志对性能的影响