StephenCleary / Mvvm

MVVM helpers, including calculated properties and asynchronous notification tasks.
MIT License
134 stars 38 forks source link

Add AsyncCommand<T> with strongly typed parameter #24

Open adamgauthier opened 5 years ago

adamgauthier commented 5 years ago

Description

In the WPF MVVM world, it is fairly common for projects to write their own simple command implementations, sometimes called DelegateCommand, RelayCommand or simply Command. Since ICommand uses object as the parameter type, it is also common for developers using CommandParameter often to implement a generic Command to avoid casting boilerplate.

For the same reason, this adds a strongly typed AsyncCommand that simply wraps an AsyncCommand, relaying CanExecutedChanged and PropertyChanged events as well as the Execute call, casting the parameter.

Example usage

XAML:

<Window x:Class="Example.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Example"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <Button
            Command="{Binding UpdateLastPickedCommand}"
            CommandParameter="{x:Static local:Fruit.Apple}"
            Content="Update Last Picked" />
    </Grid>
</Window>

c#:

using Nito.Mvvm;
using System.IO;
using System.Threading.Tasks;

namespace Example
{
    public enum Fruit { Apple }

    public class MainWindowViewModel
    {
        public MainWindowViewModel()
        {
            UpdateLastPickedCommand = new AsyncCommand<Fruit>(UpdateLastPicked);
        }

        public IAsyncCommand<Fruit> UpdateLastPickedCommand { get; }

        private Task UpdateLastPicked(Fruit fruitClicked)
        {
            return File.WriteAllTextAsync("LastFruitPicked.txt", fruitClicked.ToString());
        }
    }
}

This basically allows:

// Current way
UpdateLastPickedCommand = new AsyncCommand((fruit) => UpdateLastPicked((Fruit)fruit));

// With strongly typed AsyncCommand
UpdateLastPickedCommand = new AsyncCommand<Fruit>(UpdateLastPicked);
akamud commented 4 years ago

+1 for this