Reputation: 199
I have an items control to which i am passing an observable collection of objects and displaying the elements as buttons. I am capturing the button click in the View Model using DelegateCommands.
I want to know how i can know which button is clicked. I want to be able to pass the object associated with the button to my VM.
My 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>
My View Model:
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?
}
Upvotes: 3
Views: 4075
Reputation: 4892
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);
Upvotes: 5
Reputation: 417
The DelegateCommand should accept
Action<object>
as a constructor parameter.
Upvotes: 0