0

Here's a quick question. I have a DataGrid that looks like this:

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

I want to bind "Suggested" column cells to a command in my VM, so that each time user clicks the cell for editing, my command would execute and show a dialog for the user. I've found an interesting solution to a similar problem described here: DataGrid bind command to row select

I like the fact that it manages this from XAML without any code-behind that attaches to the cell editing event. Unfortunately, I've no idea how to convert it in a way that would allow me to bind command to cells in a specific column, rather than the entire row. Any advice in regards to that?

Community
  • 1
  • 1
L.E.O
  • 1,069
  • 1
  • 13
  • 28

1 Answers1

0

You can use BeginningEdit event in the DataGrid control to handle this scenario. This event will fires before a row or cell enters edit mode. You can identify the selected column from the EventArgs. Example:

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

If you are using MVVM pattern, there are options to pass EventArgs to VM. If you are uusing MVVMLight Toolkit, there is an option called PassEventArgs and set it to TRUE.

In VM,

//Relay Command

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

//Command Handler

private void CellBeginningEditMethod(DataGridBeginningEditEventArgs args)
        {
            if(args.Column.Header.ToString() == "Suggested")
            {
                //Do Operation
            }
        }
Dennis Jose
  • 1,589
  • 15
  • 35