thoemmi / TinyLittleMvvm

A small MVVM library for WPF built on top of MahApps.Metro, supporting .NET Framework >= 4.7.2 and .NET Core >= 3
MIT License
131 stars 22 forks source link

RelayCommand with parameters #37

Closed abrasat closed 4 years ago

abrasat commented 4 years ago

Is it possible to get parameters when executing a relay command ? For instance the "Name" property of the object issuing the command? I am using some checkboxes in an ItemsControl.ItemTemplate, and would like to be able to determine which one was checked/unchecked. Is it possible to use RelayCommand to detect a status change for a checkbox ? If yes, how to get the actual status of the checkbox (checked or unchecked)

thoemmi commented 4 years ago

Have you tried using CommandParameter binding? Here's an example at Stack Overflow which may match your issue: https://stackoverflow.com/a/42434422/4747

Do you need a command for your checkbox? Can't you just bind the Checked property to your model, and pur your logic into the property's setter?

abrasat commented 4 years ago

Thanks for the link. I cannot use the ElementName to bind to the "Name" property of the checkbox control, as there is a dynamic number of checkbox controls inside a ItemsControl.ItemTemplate. The property setter would also do the job, but I like better to use commands.

Something like this seems to work (IsSelected and Name are properties in the view-model), this is an adapted example from stackoverflow

<ItemsControl.ItemTemplate>
  <DataTemplate>
    <StackPanel Orientation="Horizontal">
      <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" Command="{Binding CheckedStatusChangedCommand}" CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}"/>
      <TextBlock Text="{Binding Name}" />
    </StackPanel>
  </DataTemplate>
</ItemsControl.ItemTemplate>

If you have a better example of how to use the commmand parameters, please put it here

thoemmi commented 4 years ago

Yes, I think passing the IsChecked as parameter to the CheckedStatusChangedCommand is the correct way. If it indeed works, great.

If your question has been answered, please close this issue.