Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass selected item as command parameter vs. using a bound ViewModel Object (MVVM)

Hopefully this is a simple MVVM question, but I'm trying to grasp command parameters.

I have a user select an item from the ListBox, and click "Delete Selected". The ListBox binds SelectedItem to "SelectedTemplate". My button XAML looks like so:

<Button CommandParameter="{Binding SelectedTemplate}" Command="{Binding DeleteTemplateCommand}" Content="Delete Selected"/>

When i get to my execute command, I'm reading the parameter from the Command. However, I also can access "SelectedTemplate". If i use the passed parameter, I'd then have to convert it to the correct objecttype before removing the object, versus just going ahead and removing "selectedTemplate"

public void DeleteTemplate(object template)
{
    Convert.ChangeType(template, typeof(Template));
    if (template == SelectedTemplate )
    {
        _ESTContext.Templates.Remove(SelectedTemplate);
    }     
}

My question here is that to me it seems both satisfy the MVVM philosophy, is there a benefit/detriment to using one or the other?

like image 817
chickenricekid Avatar asked Mar 29 '26 21:03

chickenricekid


2 Answers

The only real difference is readability (and potentially one extra binding for the engine to have to evaluate, but that isn't going to really hurt you in this case).

You are using SelectedTemplate either way so I wouldn't bother with binding it to the parameter and use it directly.

Unless that is the only thing you are using SelectedTemplate for, in which case I would toss it as a variable, and bind directly to the selection:

<Button CommandParameter="{Binding ElementName=MyListBox, Path=SelectedItem}" Command="{Binding DeleteTemplateCommand}" Content="Delete Selected"/>
like image 86
BradleyDotNET Avatar answered Apr 01 '26 08:04

BradleyDotNET


The primary benefit of using a command parameter is that you can execute the same command against different inputs, as opposed to one hard-coded input. Being able to delete any item is arguably more flexible than being able to delete just SelectedTemplate. In practice, I tend to favor using parameters.

You can avoid the cast in your "execute" callback by using a generic command implementation (i.e., something like RelayCommand<TParameter>).

like image 31
Mike Strobel Avatar answered Apr 01 '26 09:04

Mike Strobel



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!