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

基于MVVM模式的WPF DataGrid行颜色设置实现求助

实现DataGrid行颜色设置的MVVM方案

MVVM模式要求ViewModel不直接操作UI元素,所以不能直接在ViewModel里设置DataGrid行的颜色。正确的做法是通过数据驱动UI样式,具体步骤如下:

1. 给DataTable添加状态列

先在ViewModel的DataTable里新增一个用于标记行状态的列(比如命名为RowStatus),用来存储该行的结果状态:

// 初始化DataTable时添加列(需放在业务列初始化之后)
Data.Columns.Add("RowStatus", typeof(string));

2. 实现SetTheRowColor方法

这个方法不需要直接操作UI,只需要给对应DataRow的状态列赋值即可:

private void SetTheRowColor(DataRow row, bool isPass)
{
    row["RowStatus"] = isPass ? "Pass" : "Fail";
}

修改Run方法里的调用逻辑:

foreach (DataRow row in Data.Rows)
{
    bool result = Calculate(row);
    SetTheRowColor(row, result);
}

3. 在XAML中配置DataGrid的行样式

通过DataTrigger绑定到RowStatus列的值,动态设置行背景色:

<DataGrid ItemsSource="{Binding Data}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RowStatus}" Value="Pass">
                    <Setter Property="Background" Value="Green"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding RowStatus}" Value="Fail">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

补充说明

  • 如果需要自定义颜色,可以把RowStatus列的类型改成Brush,直接存储颜色对象,但推荐用字符串状态+前端样式的方式,更符合MVVM关注点分离的原则。
  • 若DataTable是动态初始化的,确保列添加完成后再绑定ItemsSource,保证UI能正确识别新增的状态列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:39:58