Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command Binding in XAML vs ICommand Properties in ViewModel

Tags:

c#

command

wpf

I am just starting to use commanding with MVVM in an application. I've found a number of examples and have tried it both ways in my code. Some examples have the command binding in the xaml like so:

<CommandBinding Command="local:MainWindow.OpenRecentFile" 
                Executed="{Binding OpenRecentFile_Executed}" />
...
<MenuItem Header="{x:Static culture:TextResource.RecentFilesMenuItem}" 
          Command="local:MainWindow.RecentFilesCommand" >

With OpenRecentFile_Executed being a method in the ViewModel and a static ICommand like so:

 public static readonly ICommand OpenRecentFile = 
     new RoutedCommand("Open Recent", typeof(MainWindow));

I have also seen where there is a property on the ViewModel that is of type ICommand that is bound to in the View like so:

<MenuItem Header="Close Current File" 
          Command="{Binding CloseCurrentFileCommand}" 
          CommandParameter="{TemplateBinding DataContext}"/>

and in the ViewModel:

private ICommand closeCurrentFileCommand;
public ICommand CloseCurrentFileCommand
{
    get
    {
        if (closeCurrentFileCommand == null)
        {
            closeCurrentFileCommand = 
                new RelayCommand(param => this.CloseCurrentCedarFile(param));
        }
        return closeCurrentFileCommand;
    }
}

What are the benefits/drawbacks to each method?

like image 709
KrisTrip Avatar asked Jul 05 '11 15:07

KrisTrip


2 Answers

I think the main difference between these is the routed nature of the first version. The routing aspect can make the command more powerful for some scenarios, but it can also cause some more pain. The pain can come into play if your trying to get the command to execute, but the target ui element does not have focus.

A property based ICommand implementation will always work because there is no "routing" step between command invocation and command delivery.

I tend to use mostly property based commands unless my scenario calls for the features that routing offers.

like image 74
NathanAW Avatar answered Oct 07 '22 15:10

NathanAW


It depends on your design. If you're going for the quick approach - a Window with back-end code then declaring commands in XAML will probably save you some time and reduce the effort in the long run.

If you are going for a MVVM app then I would strongly suggest the binding to ICommand as commands in general are ways to manipulate your data (opening/saving/editing) and this should be defined in the ViewModel. Possibly more effort depends on the functionality but MVVM is a great way to go if you're doing a larger application.

In the end both will work the same but it's your design and approach which matter.

like image 20
hyp Avatar answered Oct 07 '22 15:10

hyp