PAYATHON 2026

WPF MVVM 中如何获取 DataGrid 行按钮对应的字段值?

数据小许

在 MVVM 中,可以将按钮绑定到 ViewModel 的命令,通过 CommandParameter 传入当前行的 nestName。如果还需要 dueDate、orderStatus 等字段,也可以传入整个行对象。

为什么可以直接绑定行字段?

未另外设置 DataContext 时,DataGridTemplateColumn.CellTemplate 中按钮的 DataContext 是当前行的数据项。原代码中的 pressed.DataContext 获取的就是这个数据项。

直接绑定数据项上的字段即可,无需查找单元格或读取控件的显示文本。两个绑定的来源不同:

  • Command 来自页面的 ViewModel。
  • CommandParameter 来自按钮所在行的数据项。

将 nestName 传给 ViewModel 命令

将原来的按钮列替换为以下内容,保留现有的 DataGrid 数据源设置:

<DataGridTemplateColumn Header="Details">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button
                Content="Details"
                Command="{Binding DataContext.GetDetailsCommand,
                    RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                CommandParameter="{Binding nestName}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

这里的 RelativeSource 找到外层 DataGrid,并访问它的 DataContext.GetDetailsCommand;CommandParameter="{Binding nestName}" 则读取当前行的字段值。

这要求 DataGrid.DataContext 是暴露 GetDetailsCommand 的 ViewModel。如果 DataGrid 单独设置了其他 DataContext,需要相应调整命令的绑定来源。

以下命令实现不依赖第三方 MVVM 框架:

using System;
using System.Windows.Input;

public sealed class RelayCommand : ICommand
{
    private readonly Action<object> execute;

    public RelayCommand(Action<object> execute)
    {
        this.execute = execute;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        execute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
}

ViewModel 接收参数并交给查询逻辑:

using System;
using System.Windows.Input;

public sealed class NestViewModel
{
    public ICommand GetDetailsCommand { get; }

    public NestViewModel(Action<string> loadDetails)
    {
        if (loadDetails == null)
        {
            throw new ArgumentNullException(nameof(loadDetails));
        }

        GetDetailsCommand = new RelayCommand(parameter =>
        {
            var nestName = parameter as string;

            if (string.IsNullOrWhiteSpace(nestName))
            {
                return;
            }

            loadDetails(nestName);
        });
    }
}

示例假设 nestName 的实际类型是 string。创建 ViewModel 时,将现有的详情查询方法传给 loadDetails,并将该 ViewModel 设为视图的 DataContext。查询方法的具体实现取决于数据库访问方式。

需要多个字段时,传入整个行对象

如果详情逻辑还需要其他字段,把参数改为:

CommandParameter="{Binding}"

这样,命令接收到的就是原先 pressed.DataContext 对应的行数据项。读取字段时,需要根据数据源的实际类型处理:

  • 如果数据源是实体集合,将参数转换为对应实体类型,再访问属性。
  • 如果绑定的是 DataTable.DefaultView,行数据项通常是 DataRowView,可以通过 row["nestName"] 读取列值,并处理 DBNull.Value。

原代码没有展示数据源的具体类型,不能仅凭 TypeDescriptor.GetProperties(...) 判断该使用哪种转换方式。

绑定和查询时需要注意什么?

nestName 应与数据项实际暴露的属性名或列名一致。原代码中的 NestName.Text 是控件访问表达式,不能据此认定数据字段也叫 NestName;现有取值代码使用的是 nestName。

按钮参数绑定到当前行后,无需依赖 SelectedItem。点击某行的按钮会传递该按钮对应的数据,而当前选中行可能与它不同。

查询数据库时,应通过数据库驱动的参数机制传入 nestName,不要直接拼接进 SQL 字符串。查询耗时较长时,应使用异步查询和支持异步执行的命令,避免阻塞界面。

原先对 NestStatus.Text、NestName.Text 和 SchedFor.Text 的赋值,也可以改为更新 ViewModel 属性,让控件绑定这些属性。如果属性会在查询后变化,需要实现相应的属性变更通知,例如 INotifyPropertyChanged。

备注:内容仅供参考。