从WPF DataGrid内的按钮触发RelayCommand

Adr*_*and 12 wpf command mvvm

我有一个DataGrid显示在XAML中定义的客户列表,如下所示绑定到我的ViewModel:

<DataGrid Name="CustomersDataGrid" ItemsSource="{Binding Customers}">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Command="{Binding showCustomerCommand}" 
                        Content="{Binding Path=Name}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

网格的显示效果很好.我希望能够显示单个客户的详细信息.以前,我为所选行设置了绑定,并在页面上有一个按钮,该按钮绑定到以下命令:

RelayCommand _showCustomerCommand;
public ICommand showCustomerCommand
{
    get
    {
        if (_showCustomerCommand == null)
        {
            _showCustomerCommand = new RelayCommand(param => this.ShowCustomer());
        }
        return _showCustomerCommand;
    }
}

private void ShowCustomer()
{
    if (Parent != null)
    {
        // Handle Customer Display Here
    }
}
Run Code Online (Sandbox Code Playgroud)

这很好.但我希望能够单击单个行内的按钮,而不是基于所选行的单个按钮.我知道上面的XAML中的datacontext是错误的,但我不知道如何纠正它,也不知道如何传递按钮按下的特定行.非常感谢任何和所有建议,以帮助我连接我的嵌入式按钮!

小智 31

这会对你有所帮助

<DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <Button 
                          Command="{Binding Path=DataContext.showCustomerCommand,       
 RelativeSource= {RelativeSource FindAncestor,
  AncestorType={x:Type DataGrid}}}">
                            </Button>
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
Run Code Online (Sandbox Code Playgroud)

  • 通过解释,您将得到更多的赞成 (17认同)

Jak*_*eta 6

这个问题/答案看起来与您正在寻找的类似.

您可以将行的ID绑定到命令参数

<Button Click="Button_Click" Command="{Binding showCustomerCommand}" 
    CommandParameter="{Binding Path=ID}">View Details</Button>
Run Code Online (Sandbox Code Playgroud)

  • 这很相似,但是与后面的常规代码有关,与我尝试使用的MVVM模式无关。不过谢谢你! (2认同)