我一直在使用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()方法?
答案 0 :(得分:0)
好的用这个答案弄明白了:https://stackoverflow.com/a/30449280/4713963
只需:
更新的代码:
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>