[英]Josh Smith's Article about MVVM, WPF, C#: How to close a specific tab?
[英]c# Datagrid / Binding a button with Parameter using Josh Smith's RelayCommand class?
我一直在使用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()方法?
Ok用這個答案弄清楚了: 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.