简体   繁体   中英

Command Binding in XAML vs ICommand Properties in ViewModel

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM