Home > Backend Development > C++ > Is a Generic ICommand or RelayCommand the Best Approach for Reusable MVVM Commands?

Is a Generic ICommand or RelayCommand the Best Approach for Reusable MVVM Commands?

Mary-Kate Olsen
Release: 2025-01-20 17:30:11
Original
212 people have browsed it

Is a Generic ICommand or RelayCommand the Best Approach for Reusable MVVM Commands?

Implement commands in a reusable MVVM structure

In recent MVVM implementations, the need for multiple commands has arisen. To alleviate the tedious process of creating a single ICommand class, an alternative approach was devised. However, its effectiveness and potential improvements are yet to be discussed.

Proposed solution: Generic ICommand

In order to integrate command creation, a generic ICommand class is introduced, using delegates to execute and implement executable functions. In the constructor of this ICommand, two delegate methods are assigned. Subsequently, the ICommand method calls the delegate method.

While the functionality works, this raises the question of whether this approach is consistent with best practice, or if a more suitable solution exists.

An alternative: RelayCommand

As Karl Shifflet showed, one highly recommended method is RelayCommand. It defines an operation that is performed when called.

Example implementation of RelayCommand:

<code class="language-csharp">public class RelayCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public RelayCommand(Predicate<object> canExecute, Action<object> execute)
    {
        _canExecute = canExecute;
        _execute = execute;
    }

    // ICommand 实现...

}</code>
Copy after login

This implementation simplifies command creation, as shown in the following example:

<code class="language-csharp">public class MyViewModel
{
    public ICommand DoSomethingCommand =>
        new RelayCommand(
            p => this.CanDoSomething(),
            p => this.DoSomeImportantMethod());
}</code>
Copy after login

Other resources:

• "Patterns - WPF Applications Using MVVM Design Pattern" by Josh Smith provides further insight into the RelayCommand approach.

The above is the detailed content of Is a Generic ICommand or RelayCommand the Best Approach for Reusable MVVM Commands?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template