接受来自按钮的命令参数到 DelegateCommand

Accept command parameter from button into DelegateCommand

我有一个项目控件,我将一个可观察的对象集合传递给它,并将元素显示为按钮。我正在使用 DelegateCommands 捕获视图模型中的按钮单击。

我想知道如何知道点击了哪个按钮。我希望能够将与按钮关联的对象传递到我的 VM。

我的xaml:

<ItemsControl x:Name="list" ItemsSource="{Binding ChemList}"> //ChemList is observable collection of objects
    <ItemsControl.ItemTemplate>
        <DataTemplate>
             <Button Margin="5" 
                     Command="{Binding ElementName=list,Path=DataContext.OnBtnSelect}"
                     CommandParameter="{Binding}">
                <Button.Content>
                   <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding name}"/>
                        <TextBlock Text="    "/>
                        <TextBlock Text="{Binding num}"/>
                   </StackPanel>
                </Button.Content>
            </Button>
        </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

我的视图模型:

public DelegateCommand OnBtnSelect { get; private set; }


In the constructor:
OnBtnSelect = new DelegateCommand(OnSelect);


public void OnSelect()
{
      //How do i get here the object associated with the clicked button? 
}

DelegateCommand 应该接受

Action<object>    

作为构造函数参数。

public DelegateCommand<object> OnBtnSelect { get; private set; }

public void OnSelect(object args)
{
    //If your binding is correct args should contains the payload of the event
}

//In the constructor
OnBtnSelect = new DelegateCommand<object>(OnSelect);