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

.NET MAUI中如何更新SfDataGrid控件的指定单元格?

在.NET MAUI的Syncfusion SfDataGrid中更新长按单元格的值

核心思路

SfDataGrid基于数据绑定机制工作,不能直接通过索引操作单元格元素。正确的实现方式是更新绑定实体对应的属性,同时确保实体类实现INotifyPropertyChanged接口,这样属性变更后UI会自动同步刷新。

步骤1:让PasswrdInfo实现INotifyPropertyChanged

你的PasswrdInfo类必须实现该接口,否则属性更新后UI不会感知到变化:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class PasswrdInfo : INotifyPropertyChanged
{
    private string _passPassword;
    // 其他属性(PassId、PassTitle等)需按相同逻辑实现

    public string PassPassword
    {
        get => _passPassword;
        set
        {
            if (_passPassword != value)
            {
                _passPassword = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

步骤2:修改CellLongPress事件代码

直接更新绑定实体的PassPassword属性即可,同时修复原代码中的SQL注入风险:

private void PasswdVw_CellLongPress(object sender, DataGridCellLongPressEventArgs e)
{
    if(e.RowColumnIndex.ColumnIndex == 3)
    {
        var passData = e.RowData as PasswrdInfo;
        if (passData == null) return;

        string tmpPass, newPass;
        // 使用参数化查询避免SQL注入
        string query = "select password from PassWrds where Id = @Id";

        using(SqlConnection c = new SqlConnection(App.ConnStr))
        using(SqlCommand cmd = new SqlCommand(query, c))
        {
            cmd.Parameters.AddWithValue("@Id", passData.PassId);
            c.Open();
            var result = cmd.ExecuteScalar();
            tmpPass = result?.ToString() ?? string.Empty;
        }
    
        newPass = Crypto.Decrypt(App.secretKey, tmpPass);
        // 更新实体属性,UI会自动同步刷新
        passData.PassPassword = newPass;
    }
}

原方式报错原因

SfDataGrid没有提供PasswdVw[e.RowColumnIndex.RowIndex].Cell[3]这类直接访问单元格的API,它是数据驱动控件,所有UI展示都依赖绑定的数据源,直接操作单元格不符合其设计逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:52:46