Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a specific viewmodel object in a button's CommandParam?

I have a simple WPF program using the Master-Detail UI pattern, where the Detail shows the currently selected item of a collection in the Master pane. I'm using MVVM, and each XAML page is backed by a ViewModel object which is set as it's DataContext.

Now, I want to add a DELETE button in the Master pane to delete from the master list of items. However, I can't figure out how to pass the viewmodel object of the currently selected item as a button CommandParameter to the routed command handler code.

Thanks in advance for any pointers.

Mike


2 Answers

Something similiar to what Paul has shown is where your view model will know which item is currently selected. I.e.

public class MyVM
{
 public ObservableCollection<MyObject> MyCollection { get; set; }
 public MyObject CurrentItem { get; set; }
}

Your XAML can then be simply

CommandParameter="{Binding Path=CurrentItem}"

As long as your master pane sets the CurrentItem property when you select it, your command can simple have the CurrentItem set as the command parameter.

like image 92
Ray Booysen Avatar answered Dec 05 '25 14:12

Ray Booysen


One option would be to create each command with a reference to the view model, and create a property on the view model which is bound to the currently selected item. This way you don't need to pass the selected item as a parameter - the command can retrieve it from the VM. If this isn't suitable for your circumstances, you could pass the selected item something like this:

<Button Content="Delete"
                Command="{Binding DeleteCommand}"
                CommandParameter="{Binding ElementName=listBox_, Path=SelectedValue}" />

Where listBox_ is a control which derives from Selector.

Hope that helps,

Paul

like image 20
Paul Avatar answered Dec 05 '25 13:12

Paul



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!