【问题标题】:c# Datagrid / Binding a button with Parameter using Josh Smith's RelayCommand class?c# Datagrid / 使用 Josh Smith 的 RelayCommand 类绑定带参数的按钮?
【发布时间】:2018-03-29 21:03:21
【问题描述】:

我一直在使用 Rachel 的解决方案将按钮与命令绑定: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 : ");
}

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

【问题讨论】:

  • customerId 是什么属性?您的代码不包含其中的一个:(
  • 我的数据网格 ItemSource 绑定到 List 并且其中一个属性是 CustomerId。

标签: c# parameters binding datagrid relaycommand


【解决方案1】:

好的,答案是: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>

【讨论】:

    猜你喜欢
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2015-06-07
    • 1970-01-01
    • 2016-02-08
    • 2012-08-04
    相关资源
    最近更新 更多