You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中如何根据单元格值修改DataGrid对应行的外观

解决方案

步骤1:获取绑定的DataTable行数据

你绑定的是DataTable的DefaultView,本质是DataView类型,LoadingRow事件中e.Row.Item对应的就是当前行绑定的DataRowView对象,直接强转即可关联到原DataTable的行数据:

private void View_dg_Areas(object sender, DataGridRowEventArgs e)
{
    // 强转获取绑定的DataRowView
    DataRowView rowView = e.Row.Item as DataRowView;
    if (rowView == null) return;

    // 读取指定列的值,比如读取名为"IsEnabled"的列
    bool isEnabled = (bool)rowView.Row["IsEnabled"];
    // 也可以直接通过rowView索引取值
    // bool isEnabled = (bool)rowView["IsEnabled"];

    // 输出调试验证
    System.Diagnostics.Debug.WriteLine($"当前行IsEnabled值:{isEnabled}");
}

步骤2:根据单元格值修改行外观

拿到列值后直接修改e.Row的相关属性即可,示例:

private void View_dg_Areas(object sender, DataGridRowEventArgs e)
{
    DataRowView rowView = e.Row.Item as DataRowView;
    if (rowView == null) return;

    // 示例:当"Level"列值为3时,行背景改为浅红色,字体加粗
    int level = Convert.ToInt32(rowView["Level"]);
    if (level == 3)
    {
        e.Row.Background = Brushes.LightPink;
        e.Row.FontWeight = FontWeights.Bold;
    }
    else
    {
        // 必须给else分支恢复默认值,避免DataGrid UI虚拟化导致的滚动样式错乱
        e.Row.ClearValue(DataGridRow.BackgroundProperty);
        e.Row.ClearValue(DataGridRow.FontWeightProperty);
    }
}

注意事项

  • WPF DataGrid默认开启UI虚拟化,滚动时行控件会被复用,所以必须覆盖所有判断分支,不要只修改满足条件的行样式,否则会出现滚动后样式错乱的问题。
  • 如果列值可能为DBNull,取值前需要先做判空处理,避免抛出空引用异常。

内容的提问来源于stack exchange,提问作者Dominique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:36:03