Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept command parameter from button into DelegateCommand

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? 
}
like image 250
ilmenite Avatar asked May 08 '26 22:05

ilmenite


1 Answers

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);
like image 154
E-Bat Avatar answered May 10 '26 11:05

E-Bat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!