2017-04-26 57 views
1

我有一个项目控制,我传递一个可观察的对象集合并显示元素作为按钮。我使用DelegateCommands捕获View Model中的按钮单击。接受来自按钮的命令参数DelegateCommand

我想知道我怎么知道哪个按钮被点击。我希望能够将与按钮关联的对象传递给我的虚拟机。

我的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? 
} 
+0

您是否在使用棱镜? –

+0

是的,我正在使用棱镜 – ilmenite

+0

好的,看我的文章 –

回答

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

的DelegateCommand应该接受

Action<object>  

的构造函数的参数。