簡體   English   中英

c#Datagrid /使用喬什·史密斯的RelayCommand類將按鈕與參數綁定?

[英]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

只需:

  • 將參數作為方法參數傳遞並更新簽名
  • 與我的按鈕一起使用CommandParameter

更新的代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM