从按钮接受命令参数到DelegateCommand

时间:2017-04-26 15:15:52

标签: c# wpf xaml visual-studio-2015 prism

我有一个项目控件,我传递一个可观察的对象集合并将元素显示为按钮。我正在使用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? 
}

2 个答案:

答案 0 :(得分:2)

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);

答案 1 :(得分:0)

DelegateCommand应接受

Action<object>    

作为构造函数参数。