DataGrid绑定命令到单元格单击

时间:2013-08-16 10:36:40

标签: wpf binding datagrid triggers

这是一个简单的问题。我有一个看起来像这样的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管理它的事实,没有附加到单元格编辑事件的任何代码隐藏。不幸的是,我不知道如何以一种允许我将命令绑定到特定列中的单元格而不是整行的方式来转换它。有关于此的任何建议吗?

1 个答案:

答案 0 :(得分: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

在VM中,

//中继命令

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
            }
        }