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>
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>
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!