c#Datagrid /使用Josh Smith的RelayCommand类绑定带参数的按钮?

时间:2018-03-29 21:03:22

标签: c# parameters binding datagrid relaycommand

我一直在使用Rachel的解决方案将按钮与Command绑定:https://stackoverflow.com/a/3531935/4713963

现在我想在DataGrid中做同样的事情。

示例代码:

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

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 : ");
}

这样做我可以调用一个Command,现在我的问题是如何将CustomerId属性作为参数传递给Execute()方法?

1 个答案:

答案 0 :(得分:0)

好的用这个答案弄明白了:https://stackoverflow.com/a/30449280/4713963

只需:

  • 将param作为方法参数传递并更新签名
  • 将CommandParameter与我的按钮一起使用

更新的代码:

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()}");
}

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