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

如何将WPF DataGrid的最后一行设置为只读?

如何将WPF DataGrid的最后一行(合计行)设置为只读?

问题分析

你遇到的核心问题是WPF DataGrid没有直接的行级只读属性,之前尝试的两种方法都存在问题:

  • 第一种LoadingRow代码逻辑错误,把所有非新行都禁用了,不符合需求;
  • 第二种方法错误地试图设置DataGridRow.IsReadOnly,但该属性并不存在——只读控制是单元格级别的,而非行级别。

可行解决方案

方法1:通过BeginningEdit事件拦截编辑操作

这是最直接的方式,在编辑开始前判断当前行是否为最后一行,若为合计行则取消编辑:

  1. 在XAML中给DataGrid绑定BeginningEdit事件:
<DataGrid x:Name="dataGrid" BeginningEdit="DataGrid_BeginningEdit">
    <!-- 你的列定义 -->
</DataGrid>
  1. 后台代码实现事件处理:
private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
    int totalRows = dataGrid.Items.Count;
    // 判断当前行是否是最后一行(合计行)
    if (totalRows > 0 && e.Row.GetIndex() == totalRows - 1)
    {
        // 取消编辑请求
        e.Cancel = true;
    }
}

方法2:用CellStyle触发器动态设置单元格只读

如果偏好纯XAML实现,可以通过样式触发器结合转换器,自动识别最后一行并设置单元格只读:

  1. 定义一个转换器,用于计算最后一行的索引(总行数-1):
public class LastRowIndexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int rowCount && rowCount > 0)
        {
            return rowCount - 1;
        }
        return -1;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
  1. 在XAML资源中声明转换器:
<Window.Resources>
    <local:LastRowIndexConverter x:Key="LastRowIndexConverter"/>
</Window.Resources>
  1. 给DataGrid设置包含触发器的CellStyle:
<DataGrid x:Name="dataGrid">
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <!-- 当行的显示索引等于最后一行索引时,设置单元格只读 -->
                <DataTrigger 
                    Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Path=DisplayIndex}"
                    Value="{Binding ElementName=dataGrid, Path=Items.Count, Converter={StaticResource LastRowIndexConverter}}">
                    <Setter Property="IsReadOnly" Value="True"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
    <!-- 你的列定义 -->
</DataGrid>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:32:12