How to pass a specific viewmodel to a CommandParam button?

I have a simple WPF program using the Master-Detail user interface template, where Detail shows the currently selected collection item in the Master panel. I use MVVM, and each XAML page is supported by a ViewModel that is set as a DataContext.

Now I want to add a DELETE button on the Master panel to remove it from the main list of items. However, I cannot understand how to pass the viewmodel of the currently selected item as a CommandParameter button to the routed command handler code.

Thanks in advance for any pointers.

Mike

+3
source share
2 answers

Something similar to what Paul showed is where your look 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 might just be

CommandParameter="{Binding Path=CurrentItem}"

As long as your master panel sets the CurrentItem property when it is selected, your team can simply set CurrentItem as the command parameter.

+2
source

One option is to create each command with a link to the view model and create a property in the view model that is bound to the currently selected item. Thus, you do not need to pass the selected item as a parameter - the command can retrieve it from the virtual machine. If this is not suitable for your circumstances, you can pass the selected item something like this:

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

listBox_ - , .

, ,

+1

Source: https://habr.com/ru/post/1702911/


All Articles