0

这是一个快速的问题。我有一个看起来像这样的 DataGrid:

<DataGrid ItemsSource="{Binding Path=Sections}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=ImportName, Mode=OneWay}" Header="Imported" />
        <DataGridTextColumn Binding="{Binding Path=FoundName, Mode=TwoWay}" Header="Suggested" />
    </DataGrid.Columns>
</DataGrid>

我想将“建议”列单元格绑定到我的 VM 中的命令,以便每次用户单击单元格进行编辑时,我的命令都会执行并为用户显示一个对话框。对于此处描述的类似问题,我找到了一个有趣的解决方案:DataGrid bind command to row select

我喜欢它从 XAML 管理这个的事实,而没有任何附加到单元格编辑事件的代码隐藏。不幸的是,我不知道如何将它转换为允许我将命令绑定到特定列中的单元格,而不是整行。对此有什么建议吗?

4

1 回答 1

0

您可以使用控件BeginningEdit中的事件DataGrid来处理这种情况。此事件将在行或单元格进入编辑模式之前触发。您可以从 EventArgs 中识别选定的列。例子:

private void dgName_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            if (e.Column.Header.ToString() == "Suggested")
            {
                //Do Operation
            }
        }

如果您使用 MVVM 模式,则可以选择将 EventArgs 传递给 VM。如果您正在使用 MVVMLight Toolkit,则有一个名为的选项PassEventArgs并将其设置为TRUE.

在虚拟机中,

//中继命令

private RelayCommand<DataGridBeginningEditEventArgs> _cellBeginningEditCommand;
    public RelayCommand<DataGridBeginningEditEventArgs> CellBeginningEditCommand
    {
        get
        {
            return _cellBeginningEditCommand ?? (_cellBeginningEditCommand = new RelayCommand<DataGridBeginningEditEventArgs>(CellBeginningEditMethod));
        }
    }

//命令处理程序

private void CellBeginningEditMethod(DataGridBeginningEditEventArgs args)
        {
            if(args.Column.Header.ToString() == "Suggested")
            {
                //Do Operation
            }
        }
于 2013-08-16T17:43:52.503 回答