I have a datagrid bound to an observable collection of objects. What I want to do is have a button that will execute a method of the object representing the row of the button that was clicked. So what I have now is something like this:
<DataGridTemplateColumn Header="Command">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="cmdCommand" Click="{Binding Command}"
Content="Command"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Which doesn't work and reports the following error:
Click="{Binding Command}" is not valid. '{Binding Command}' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid.
I've looked at command binding but that looks like it would just end up going to a single external command instead of to the object bound to the row. I have it working using an event handler on the code behind and then routing it to the item bound to the selected row (since the row gets selected when the button is clicked) but that seems like poor way of handing this and I assume I'm just missing something here.
Best Answer
I do this all the time. Here's a look at an example and how you would implement it.
Change your XAML to use the Command property of the button instead of the Click event. I am using the name SaveCommand since it is easier to follow then something named Command.
Your CustomClass that the Button is bound to now needs to have a property called SaveCommand of type
ICommand
. It needs to point to the method on the CustomClass that you want to run when the command is executed.The above code uses a RelayCommand which accepts two parameters: the method to execute, and a true/false value of if the command can execute or not. The RelayCommand class is a separate .cs file with the code shown below. I got it from Josh Smith :)