0

I've been using Rachel's solution to bind a button with a Command : https://stackoverflow.com/a/3531935/4713963

Now I would like to do the same within a DataGrid.

Sample code :

<DataGrid.Columns>
    <DataGridTemplateColumn Header="CustomerID">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Content="{Binding CustomerId}"
                    Command="{Binding DataContext.DetailCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

with

private ICommand _detailCommand;

public ICommand DetailCommand
{
    get
    {
    if (_detailCommand == null)
    {
        _detailCommand = new RelayCommand(
        param => this.Execute(),
        );
    }
    return _detailCommand;
    }
}

private void Execute()
{
    MessageBox.Show("Selected CustomerId : ");
}

Doing so I can invoke a Command, now my question is how to pass the CustomerId property as a parameter to the Execute() method ?

Coloris
  • 35
  • 8

1 Answers1

0

Ok figured it out with this answer : https://stackoverflow.com/a/30449280/4713963

Just had to :

  • Pass param as a method parameter and update the signature
  • Use CommandParameter with my button

Updated code :

private ICommand _detailCommand;

public ICommand DetailCommand
{
    get
    {
    if (_detailCommand == null)
    {
        _detailCommand = new RelayCommand(
        param => this.Execute(param),
        );
    }
    return _detailCommand;
    }
}

private void Execute(object param)
{
    MessageBox.Show($"Selected CustomerId : {param.ToString()}");
}

and

<DataGrid.Columns>
    <DataGridTemplateColumn Header="CustomerID">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Content="{Binding CustomerId}"
                Command="{Binding DataContext.DetailCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}"
                CommandParameter="{Binding CustomerId}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>
Coloris
  • 35
  • 8