3

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 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.