Search code examples
wpfdata-bindingmvvmbuttonrouted-commands

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


Solution

  • 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.