wpf - 从 WPF DataGrid 中的按钮触发 RelayCommand

标签 wpf mvvm command

我有一个 DataGrid显示在 XAML 中定义的客户列表,如下所示绑定(bind)到我的 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>

网格的显示工作正常。我希望能够显示单个客户的详细信息。以前,我为选定的行设置了一个绑定(bind),并在页面上有一个绑定(bind)到以下命令的按钮:

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

这工作得很好。但我希望能够单击单个行内的按钮,而不是基于选定行的单个按钮。我知道上述 XAML 中的数据上下文是错误的,但我不知道如何更正它,也不知道如何传递按钮按下的特定行。任何和所有帮助我连接我的嵌入式按钮的建议都非常感谢!

最佳答案

这将帮助你

<DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <Button 
                          Command="{Binding Path=DataContext.showCustomerCommand,       
 RelativeSource= {RelativeSource FindAncestor,
  AncestorType={x:Type DataGrid}}}">
                            </Button>
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>

关于wpf - 从 WPF DataGrid 中的按钮触发 RelayCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12179701/

相关文章:

Unix uniq、sort 和 cut 命令删除重复行

c# - 如何使用 ObjectDataProvider 将枚举绑定(bind)到 XAML 中的 ComboBox

.net - Windows.Forms 等同于 Arrange、Measure 和 DesiredSize?

c# - 如何绑定(bind)到集合集合下的对象的属性?

c# - XAML 中的动画按钮背景颜色

c# - WPF MVVM 可观察集合不更新 GUI

Python - 打开新的 shell 并运行命令

ffmpeg - 如何使用 FFMPEG 和 Xfade 将两个 png 转换为透明 webm 视频

c# - MVVM 如何将 ListBox SelectedItem 放入 ViewModel 中的类的实例中

c# - 使用 Observable Collection MVVM 绑定(bind) Pivot 控件(windows phone 8)