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

C# WPF中如何编辑DataGrid控件的单元格?

C# WPF DataGrid单元格编辑实现方法

WPF的设计思路和WinForms有本质区别,WinForms支持直接操作控件的单元格视图,WPF优先推荐数据驱动的绑定方案,也可兼容直接操作控件的写法,两种实现如下:

方案1:数据绑定实现(官方推荐最优实践)

  • 首先定义实现INotifyPropertyChanged接口的数据模型,属性变更会自动同步到UI:
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class DataItem : INotifyPropertyChanged
{
    private string _customField;
    // 对应DataGrid要编辑的列属性
    public string CustomField
    {
        get => _customField;
        set 
        { 
            _customField = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  • 给DataGrid绑定ObservableCollection<DataItem>类型的数据源:
// 窗口类或视图模型中定义数据源
public ObservableCollection<DataItem> DataSource { get; set; } = new ObservableCollection<DataItem>();

// 初始化时关联DataGrid
myDataGrid.ItemsSource = DataSource;
  • 编辑单元格直接修改数据源对应值即可,UI会自动更新,等价于WinForms的写法:
// 编辑第0行第2列对应的属性值
DataSource[0].CustomField = "xxxx";

方案2:直接操作控件(仅临时场景使用,不推荐)

如果不需要绑定逻辑,想要和WinForms一样直接操作控件单元格,可使用如下代码,注意开启UI虚拟化时该方式可能失效:

// 获取第0行对象
DataGridRow targetRow = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromIndex(0);
if (targetRow != null)
{
    // 获取第2列的单元格对象
    DataGridCell targetCell = myDataGrid.Columns[2].GetCellContent(targetRow)?.Parent as DataGridCell;
    if (targetCell != null && targetCell.Content is TextBlock textBlock)
    {
        // 赋值
        textBlock.Text = "xxxx";
    }
}

注意:直接操作控件的写法没有修改数据源,滚动DataGrid或者刷新数据后修改的值会被还原,仅适合临时调试场景使用。

相关图示1
相关图示2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:45:02