我有一个 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/